android获取控件宽高

来源:互联网 发布:点明安卓读屏软件 编辑:程序博客网 时间:2024/05/28 09:33

平时直接用 getWidth()和getHeight() 两个方法来直接控件的宽高,结果会为0

可采用以下三种获取方式:

@Override    public void onWindowFocusChanged(boolean hasFocus)    {        super.onWindowFocusChanged(hasFocus);        if (hasFocus)        {            int width = image.getMeasuredWidth();            int height = image.getMeasuredHeight();        }    }

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

 ViewTreeObserver observer = image.getViewTreeObserver();        observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener()        {            @Override            public void onGlobalLayout()            {                image.getViewTreeObserver().removeGlobalOnLayoutListener(this);                int width = image.getMeasuredWidth();                int height = image.getMeasuredHeight();            }        });


0 0
原创粉丝点击