您的位置:首页 > 移动开发 > Android开发

android获取控件宽高

2016-01-22 15:18 281 查看
平时直接用 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();
            }
        });
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: