关于 View 的知识

View的getWidth()和getMeasuredWidth()有什么区别吗?

从名字上可以看出,measuredWidth/height 是用在测量和布局之间的阶段。

举例说明:

父控件要求子控件测量它自己,子控件说,我需要 200 像素 x 200 像素的空间。这就是 measuredWidth/height。

在布局阶段期间,如:在 onLayout 方法。这个方法可以使用它的子控件的 measuredWidth/height 或者通过调用 view 的 layout 方法重新发配新的 width/height。

现在,我们可以得知, onLayout方法调用 childview.layout(0,0,150,150),这个 View 的 width/height 和 mersured width/height 是不同的(0,0,150,150 是重新赋值的)。

不建议在 onLayout方法外使用 measuredWidth/height。

总结:

  1. onMeasure -> 设置 measuredWidth/measuredHeight
  2. onLayout -> 设置控件中的 width/height

此外,

public void View.layout(int l, int t, int r, int b)

似乎是位置分配和大小的发生赋值(assignment)的地方。

原链接:在 Android SDK 中,getWidth/Height() 和 getMeasuredWidth/Height() 之间有什么不同

如何在onCreate中拿到View的宽度和高度?

根据你的目标,你可以使用布局或者绘制前的监听。例如,在 onCreate() 中:

1
2
3
4
5
6
7
8
9
10
11
12
final View content = findViewById(android.R.id.content);
content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// 如果你从这个方法里面修改这个布局,除非你想把「每一个」布局传递到
//这个回调里,它会使你进入无限循环,否则,移除它。
content.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// 现在你可以从 content View 中得到宽和高
}
});

原链接:如何在 onCreate 方法中,拿到 View 的大小

坚持原创技术分享,您的支持将鼓励我继续创作!