View的getWidth,getHeight为0的解决方法

来源:互联网 发布:c语言atm机程序 编辑:程序博客网 时间:2024/05/17 22:52

在Activity文件中就可以重写onWindowFocusChanged方法,在该方法中获得view的width和height

@Override    public void onWindowFocusChanged(boolean hasFocus) {        super.onWindowFocusChanged(hasFocus);        textview.getHeight();}

Fragment中不能重写onWindowFocusChanged方法,因此可以使用ViewTreeObserver来添加一个回调,在回调中获得view的width和height

ViewTreeObserver vto = textview.getViewTreeObserver();        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {            public boolean onPreDraw() {                int height = textview.getMeasuredHeight();                int width = textview.getMeasuredWidth();                return true;            }        });
0 0
原创粉丝点击