You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/**
* view 布局改变时
*/
private void getHeight4() {
tvText.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
tvText.removeOnLayoutChangeListener(this);
int height = tvText.getHeight();
Log.i(TAG, "MainActivity;getHeight4;height=" + height);
}
});
}
Reacted by 君不见jj, Linsea, Supr3me, chen3441251, senlinxuefeng, Jackie-a and shark fly
获取方法:
a. getWidth() 和 getHeight() 方法,本质上是等view宽高计算结束,取内存的值。
b. getMeasureWidth 和 getMeasureHeight 方法,本质上是measure结束,取内存的值。
c. View 的宽高本身是可以写死的。那么就可以直接 取值。任何时机结果都是对的。【例如铺满横屏,有时候可以取屏幕宽度】
d. 取业务缓存。这个依据特定场景,例如:同一个手机,上下滑动直播间,共用的同一个Activity,那么界面的高度,是可以复用的。即:第一次获取完成之后,就可以一直用这个高度值。
Activity
DaveBoy commentedon Aug 28, 2019
view.post一个就行了 一把梭
zhaoerlei1989 commentedon Aug 28, 2019
1.OnGlobalLayoutListener获取
2.OnPreDrawListener获取
3.OnLayoutChangeListener获取
4.重写View的onSizeChanged()
5.使用View.post()方法
uarenothingx commentedon Aug 28, 2019
使用MessageQueue.addIdleHandler()也可以获取,而且可以防止多次调用。
gabyallen commentedon Aug 28, 2019
使用View.post()方法
Context.runOnUiThread(new Runnable()
OnGlobalLayoutListener获取
OnPreDrawListener获取
OnLayoutChangeListener获取
重写View的onSizeChanged()
huazidev commentedon May 30, 2020
先说下问题的考点:
首先,在 view 测量过后就可以获得 view 的测量宽高,另外系统可能需要多次 measure 才能确定最终的测量宽高。
其次,由于 view 的测量过程和 Activity 的生命周期不是同步,所以无法保证在 onCreate,onStart, onResume 时已经测量完毕,如果没有测量完毕获取的宽高都是0。
能获取真实 view 宽高的方法:
liyanfei250 commentedon Dec 23, 2020
1 通过 looper 队列
2 当视图树的布局发生改变时
3 当视图树的进行绘制时
4 view 布局改变时
mlinqirong commentedon Dec 20, 2021
通过view.post Runnable方法里面通过view.getHeight
yline commentedon Sep 2, 2023
看了上方的回答,发现“答不对题”;题目是:获取View宽高的几种方法;回答应该是获取方法,而上文回答的全是”获取时机“
a. getWidth() 和 getHeight() 方法,本质上是等view宽高计算结束,取内存的值。
b. getMeasureWidth 和 getMeasureHeight 方法,本质上是measure结束,取内存的值。
c. View 的宽高本身是可以写死的。那么就可以直接 取值。任何时机结果都是对的。【例如铺满横屏,有时候可以取屏幕宽度】
d. 取业务缓存。这个依据特定场景,例如:同一个手机,上下滑动直播间,共用的同一个Activity,那么界面的高度,是可以复用的。即:第一次获取完成之后,就可以一直用这个高度值。