android view宽高确定

来源:互联网 发布:众测平台数据安全 编辑:程序博客网 时间:2024/06/16 05:20

1、onWindowFocusChanged:

view己经初始化完毕,宽高己经准备好。当Activity得到焦点和失去焦点均会被调用,所以它会调用多次。

2、通过view.post

将一个runnable投弟到消息队列尾部,等待looper调用时,view己经初始化好。

protected void onStart(){    super.onStart();    view.post(new Runnable(){        public void run(){            int width = view.getMeasuredWidth();            int height = new .getMeasuredHeight();        }    })}

3、ViewTreeObserver:

使用ViewTreeObserver众多回调接口来完成,如OnGlobalLayoutListener,当view树状态发生改变时或内部view可见性发生改变时会回调。

ViewObserver obserber = view.getViewObserver ();obserber.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){    public void onGlobalLayout(){        obserber.removeOnGlobalLayoutListener(this);        int width = view.getMeasuredWidth();        int height = new .getMeasuredHeight();    }})

4、通过view进行measure来得到view的宽高。

int width = MeasureSpec.makeMeasureSpec(100,Measure.EXACTLY);//确定值int height= MeasureSpec.makeMeasureSpec(100,Measure.EXACTLY);//确定值view.measure(width,height);//对于wrap_content:int width = MeasureSpec.makeMeasureSpec((1<<30)-1,Measure.AT_MOST);//wrap_contentint height= MeasureSpec.makeMeasureSpec((1<<30)-1,Measure.AT_MOST);//wrap_contentview.measure(width,height);

5、自定义view中注意事项

自定义View需要注意的事项:
如果是继承view或者viewGroup,让view支持wrap_content。
如果有必要,让view支持padding。
View中如果有动画或者线程,要在onDetachedFromWindow中及时停止。当view的Activity退出或者当前view被remove时,调用它。

0 0
原创粉丝点击