android - LinearLayout.getWidth() 不反射(reflect)来自 setLayoutParams 的新宽度

标签 android android-layout layoutparams

tl/dr

I am trying to change some layouts sizes in code, and I can change some of them, but the other ones that needed to update based on the changes won't update together. Instead, they retain the previous width that the changed ones had.

因此,我正在使用 Android Studio 并尝试以编程方式更改某些 LinearLayouts 的大小。

这就是我正在做的:

final LinearLayout ll3 = (LinearLayout)findViewById(R.id.box3);
ViewGroup.LayoutParams p3 = ll3.getLayoutParams();
int w3 = 5;
float aux = (float)w3/15;
p3.width = Math.round(max*aux);
ll3.setLayoutParams(p3);

然后这就是我得到的:

Log.i("OnLongClick p3_width", Integer.toString(p3.width));
Log.i("OnLongClick ll3_getWidth", Integer.toString(ll3.getWidth()));

OnLongClick p3_width﹕ 179

OnLongClick ll3_getWidth﹕ 224

ll3.getWidth() 正在返回之前的值,这是 ll3 在设置新参数之前的值。 如果我重复这个过程,那么它会显示如下内容:

OnLongClick p3_width﹕ 314 //New Value

OnLongClick ll3_getWidth﹕ 179 //Old (previous) Value

我需要 ll3.getWidth() 与 p3.width 相同,因为我在另一个函数中调用它以重新计算我的应用程序具有的其他 LinearLayouts。否则,当应用程序重绘时,手动更改的矩形会发生变化,但其他矩形(使用更改修改自身)将保持以前更改的方式(对这句话感到抱歉)。

我认为发生这种情况是因为 setLayoutParams 必须及时进一步完成它的工作,而不是在我调用 getWidth() 之前,但我不知道这是否真的是问题所在,以及如何解决它。

感谢任何帮助。

提前致谢!!!

编辑 2: 如果我发送

openOptionsMenu();
closeOptionsMenu();

它固定了矩形的大小。但是,它会延迟执行此操作,因此非常难看。 无论如何,我需要将任何东西放在 openOptionsMenu() 中间来解决这个问题(closeOptionsMenu() 不会改变 View ,只会关闭菜单)。

最佳答案

找到答案了!!!就像很多次一样,它就在我的脸上。

发生的事情是 p3.width 只不过是 ll3.getLayoutParams().width。 所以,我现在调用 ll3.getLayoutParams().width,而不是调用 ll3.getWidth()(它返回了错误的宽度),然后它将正确地生成计算。

我仍然不知道为什么 ll3.getWidth() 会返回一个错误的值,但至少它是有效的(不过,如果你知道为什么,也请告诉我!! !)。

关于android - LinearLayout.getWidth() 不反射(reflect)来自 setLayoutParams 的新宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28322436/

相关文章:

android - 将 Android 连接到 Python

Android:自定义Toast通知继承默认Toast

android - 如何在android中获取显示图像的宽度和高度?

android - 使相对布局的内容大于屏幕

android - Android Studio 中的 fragment_main 和 activity_main 布局

android - ICS 中的 TYPE_SYSTEM_OVERLAY

android - 使用 LinearLayout.LayoutParams 将 WRAP_CONTENT 更改为设定的数字

javascript - 永久唯一移动设备标识符(Evercookie?)

java - 如何使Android BottomNavigationView背景透明?

java - 在 SoundCloud Android 应用程序中使用 Facebook 和 Google Plus 登录