改变的LayoutParams对象的属性后,我需要再次调用setLayoutParams? [英] After changing a property on a LayoutParams object, do I need to call setLayoutParams again?

查看:605
本文介绍了改变的LayoutParams对象的属性后,我需要再次调用setLayoutParams?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图(含广告),我需要扩展以适应屏幕宽度在某个时间点(加载广告后)。所以,我有一个方法自动调用setHeight(MyView的),计算正确的高度为给定的屏幕宽度,并更改视图的的LayoutParams相应。的code中的关键部分是这样的:

I have a View (containing an ad) that I need to scale to fit the screen width at a certain point in time (after the ad is loaded). So I have a method setHeight(myView) that calculates the correct height for the given screen width and changes the LayoutParams of the View accordingly. The crucial part of the code is this:

LayoutParams params = myView.getLayoutParams();
int width = myView.getWidth();
if (params != null && width > 0) {
    params.height = (int) Math.round(ratio * width);
}

这似乎工作的大部分,但有时视图不进行缩放。它似乎只consistenly工作,如果我添加以下行底部:

This seems to work for the most part, but sometimes the view is not scaled. It seems to only consistenly work if I add the following line at the bottom:

myView.setLayoutParams(params);

这似乎是有道理的,也由于Android查看呼叫 requestLayout()在他们 setLayoutParams()方法。相反,我看不出有什么办法如何在公共领域的变化( params.height )将触发布局的变化。

This seems to make sense, too, since Android Views call requestLayout() in their setLayoutParams() method. Conversely, I see no way how a change in a public field (params.height) would trigger a layout change.

在另一方面,我反复查找在何处PARAMS被简单地改变,然后没有设置为视图再次净教程。

On the other hand, I repeatedly find tutorials on the net where the params are simply changed and then not set to the view again.

所以,我的问题是:是否纠正,改变的LayoutParams的属性后立即更新布局,我需要调用 setLayoutParams 了吗?而这仅仅改变属性只会导致在之后的某个时间点的布局变化时布局的变化是从其他地方触发?

So, my question is: Is it correct that, to immediately update the layout after changing a property of the LayoutParams, I need to call setLayoutParams again? And that simply changing the property will only lead to a layout change at some later point in time when the layout change is triggered from elsewhere?

推荐答案

一个改变的布局只PARAMS在下次布局传递效果。

A change to the layout params only take effect on the next layout pass.

  • requestLayout()时间表布局通

setLayoutParams()电话 requestLayout()为您所观察到

有时候,一个布局传递计划通过其他方式。例如,立即充气后的布局PARAMS也被夸大和措施/布局的消息刚刚公布,为以后处理UI线程消息队列。

Sometimes a layout pass is scheduled by some other means. For example, immediately after inflation the layout params have also been inflated and the measure/layout message has just been posted to the UI thread message queue for later processing.

所以,为了安全起见,调用 requestLayout()在触摸布局PARAMS后。 setLayoutParams()的作品也是如此,虽然它就地修改PARAMS时候是不是绝对必要的。

So, to be safe, call requestLayout() always after touching the layout params. setLayoutParams() works, too, though it's not strictly necessary when modifying the params in-place.

这篇关于改变的LayoutParams对象的属性后,我需要再次调用setLayoutParams?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆