在 fragment View 中,我想根据包含 View 的宽度调整其中一个 subview 的布局参数,其布局参数设置为 match_parent。我需要做的是为父 View 调用getWidth/getHeight,然后设置 subview 的ViewGroup.LayoutParameters等。
问题是 getWidth 只会在第一次绘制布局后返回有效值,我不确定是否有任何 fragment 覆盖可用于执行此操作。例如, View 的实际宽度在调用 onCreateView 或 onStart 时未确定。
那么有没有一种直接的方法来实现它,或者我必须继承一个 View 并重写 onLayout 或 onMeasure?
最佳答案
您可以在 View 树上设置一个全局布局监听器并在其中进行操作。
final ViewTreeObserver vto = myView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
// do layout tweaking based on measurements
// remove the listener... or we'll be doing this a lot.
vto.removeGlobalOnLayoutListener(this);
}
}
关于android - 布局参数的运行时调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146633/