开发小技巧之进入Activity之后获取控件高度

来源:互联网 发布:网络打印机通讯协议 编辑:程序博客网 时间:2024/06/06 04:42

1.在开发过程中我们有时候需要一进入Activity的时候,就能够获取到控件的高度,
你过你细心的话去在onCreate或者onResume 中加入

   height = iv.getHeight();   Log.i("height","height=>"+height);

执行过后发现高度的0,相应的宽度也是0.

这就奇怪了为什么控件的高度,宽度为0 呢,应该Activity在启动的时候,是存在Activity启动流和Activity布局绘制流,但是这两个流是异步,也就是说,在onCreate或者onResume 的时候控件的Activity布局绘制流 这个异步任务可能没有执行完毕,这个时候你去获取控件的高度,获取的是控件高度的默认值,就0。


获取控件高度的方法:

/** * 为Activity的布局文件添加OnGlobalLayoutListener事件监听,当回调到onGlobalLayout方法的时候我们通过getMeasureHeight和getMeasuredWidth方法可以获取到组件的宽和高 */private void initOnLayoutListener() {        final ViewTreeObserver viewTreeObserver = this.getWindow().getDecorView().getViewTreeObserver();        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {            @Override            public void onGlobalLayout() {                Log.i(TAG, "开始执行onGlobalLayout().........");                int height = titleText.getMeasuredHeight();                int width = titleText.getMeasuredWidth();                Log.i(TAG, "height:" + height + "   width:" + width);           // 移除GlobalLayoutListener监听                        MainActivity.this.getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);            }        });    }

执行这个方法,只是为了使OnGlobalLayoutListener,执行一次

MainActivity.this.getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
原创粉丝点击