码迷,mamicode.com
首页 > 移动开发 > 详细

android获取view宽高的几种方法

时间:2014-08-20 16:14:52      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   color   2014   div   log   

在onCreate方法中我们通过mView.getWidth()和mView.getHeight()获取到的view的宽高都是0,那么下面几种方法就可以在onCreate方法中获取到view的宽高。

1、

        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        mTextView.measure(w, h);
        int height = mTextView.getMeasuredHeight();
        int width = mTextView.getMeasuredWidth();
        System.out.println("measure width=" + width + " height=" + height);

2、mViewTreeObserver = mTextView.getViewTreeObserver();

        mViewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                // TODO Auto-generated method stub
                mTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                System.out.println("onGlobalLayout width=" + mTextView.getWidth() + " height=" + mTextView.getHeight());
            }
        });

3、

        mViewTreeObserver.addOnPreDrawListener(new OnPreDrawListener()
        {
            @Override
            public boolean onPreDraw()
            {
                // TODO Auto-generated method stub
                mTextView.getViewTreeObserver().removeOnPreDrawListener(this);
                System.out.println("onPreDraw width=" + mTextView.getWidth() + " height=" + mTextView.getHeight());
                return true;
            }
        });

4、

    @Override
    public void onWindowFocusChanged(boolean hasFocus)
    {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus)
        {
            System.out.println("onWindowFocusChanged width=" + mTextView.getWidth() + " height=" + mTextView.getHeight());
        }
    }

打印结果:

bubuko.com,布布扣

android获取view宽高的几种方法,布布扣,bubuko.com

android获取view宽高的几种方法

标签:android   style   blog   http   color   2014   div   log   

原文地址:http://www.cnblogs.com/yushilong/p/3924741.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!