在onCreate方法中获取某个View的宽度和高度

来源:互联网 发布:spring实战 知乎 编辑:程序博客网 时间:2024/06/06 09:53

来源:http://chenfeng0104.iteye.com/blog/1186850


有时候需要在onCreate方法中知道某个View组件的宽度和高度等信息,而直接调用View组件的getWidth()、getHeight()、getMeasuredWidth()、getMeasuredHeight()、getTop()、getLeft()等方法是无法获取到真实值的,只会得到0。这是因为View组件布局要在onResume回调后完成。下面提供实现方法,onGlobalLayout回调会在布局完成时自动调用。


final LinearLayout imageViewContainer = (LinearLayout)findViewById(R.id.crop_photo_image_view_container);          imageViewContainer.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {              boolean isFirst = true;//默认调用两次,这里只让它执行一次回调              @Override              public void onGlobalLayout() {                  if (isFirst) {                      isFirst = false;                      //现在布局全部完成,可以获取到任何View组件的宽度、高度、左边、右边等信息                      Log.i("CDH", "Global W:"+imageViewContainer.getMeasuredWidth()+"  H:"+imageViewContainer.getMeasuredHeight());                  }              }          });  





0 0
原创粉丝点击