Android开发中,onCreate()、onStart()、onResume()关键生命周期方法中获取某控件的宽高,然而获取的结果均为 0,Why?
Because:View的measure()与Activity的生命周期没有同步执行,因此不能保证在onCreate()、onStart()、onResume()中获取控件宽高时,这个View已经测量结束,so,如果没有测量完成,我们取得的宽高就是0。
Activity中测试代码,具体看注释即可:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button button;// Activity获取View的宽高
private boolean isFirstFocus = true;
private int hightBtn, widthBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// View的measure()过程和Activity的生命周期方法不是同步执行的
// 无法保证Activity执行了onCreate()、onStart()、onResume()时某个View已经测量完毕
hightBtn = button.getHeight();
widthBtn = button.getWidth();
//code1 button's Height:0,Width:0
Log.d(TAG, "code1 button's Height:" + hightBtn + ",Width:" + widthBtn);
// 手动调用View的measure()方法后获取——具体值模式可用,此处match_parent无效
int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY);
int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY);
button.measure(width, height);
hightBtn = button.getMeasuredHeight();
widthBtn = button.getMeasuredWidth();
// code2 button's Height:0,Width:0
Log.d(TAG, "code2 button's Height:" + hightBtn + ",Width:" + widthBtn);
// 手动调用View的measure()方法后获取——wrap_content可用
width =Vi

在Android开发中,由于View的测量与Activity的生命周期不同步,直接在关键生命周期方法中获取控件宽高可能得到0。本文介绍了4种有效获取View宽高的方法:view.post(runnable),view.addOnLayoutChangeListener(),ViewTreeObserver#addOnGlobalLayoutListener(),以及Activity/View#onWindowFocusChanged()。同时,讨论了手动调用measure方法后如何正确获取View的宽高,包括处理LayoutParams的不同模式。
最低0.47元/天 解锁文章
1592

被折叠的 条评论
为什么被折叠?



