gpt4 book ai didi

android - 设置权重后如何获取 MeasuredWidth()

转载 作者:行者123 更新时间:2023-11-29 00:44:38 28 4
gpt4 key购买 nike

我举了一个简单的例子来说明问题。这是一个简单的 LinearLayout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>

然后我在 onCreate() 中填充它

private final String TAG = getClass().getSimpleName();

ImageView iv1;
ImageView iv2;
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout container = (LinearLayout) findViewById(R.id.ll);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.weight=1.0f;

iv1 = new ImageView(this);
iv1.setImageResource(R.drawable.icon);

iv2 = new ImageView(this);
iv2.setImageResource(R.drawable.icon);

container.addView(iv1, lp);
container.addView(iv2, lp);

container.measure(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
Log.d(TAG, " measured width(1): " + iv1.getMeasuredWidth());
Log.d(TAG, " measured width(2): " + iv2.getMeasuredWidth());

其中图标是 48x48dp 的简单图像。问题是:为什么 getMeasuredWidth 在日志中返回 48,但当我查看层次结构查看器时 mMeasureWidth 是 160?换句话说,真正的问题是......当 View 在 LinearLayout 中拉伸(stretch)时,如何获得 View 的实际宽度/高度(在 Java 中)?调用requestLayout()、measure()不起作用。我可以尝试获得权重的总和并计算 LinearLayout 所做的一切,但也许有更优雅的解决方案。

最佳答案

onCreate 在 Activity 显示之前被调用。

因此,iv1.getMeasuredWidth() 还不是您期望的值,应该稍后在另一个方法中调用。我认为 onWindowFocusChange 是正确的。

关于android - 设置权重后如何获取 MeasuredWidth(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7079824/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com