获取某个view的高度或者宽度

方法一

在activity的onWindoFocusChanged中获取宽高.此方法会被调用多次.在activity得到焦点或者失去焦点的时候均会调用.代码如下

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus){
            int width=testBtn.getMeasuredWidth();
            int height=testBtn.getMeasuredHeight();
            Log.d(TAG, "onWindowFocusChanged: width="+width);
            Log.d(TAG, "onWindowFocusChanged: height="+height);
        }
    }

方法二

通过post将一个runnable投递到消息队列尾部
代码如下:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_touch_test);
        testBtn= findViewById(R.id.btn_test);
        testBtn.post(new Runnable() {
            @Override
            public void run() {
                int width=testBtn.getMeasuredWidth();
                int height=testBtn.getMeasuredHeight();
                Log.d(TAG, "onWindowFocusChanged: width="+width);
                Log.d(TAG, "onWindowFocusChanged: height="+height);
            }
        });
    }

方法三

ViewTreeObserver
使用ViewTreeObserver的众多回调可以完成这个功能,比如使用onGlobalLayoutListener这个接口.当view树发生改变,或者View树内部的view的可见性发生改变时,此方法将被调用.此方法可能会被调用多次:

    @Override
    protected void onStart() {
        super.onStart();
        ViewTreeObserver viewTreeObserver=testBtn.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int width=testBtn.getMeasuredWidth();
                int height=testBtn.getMeasuredHeight();
                Log.d(TAG, "onWindowFocusChanged: width="+width);
                Log.d(TAG, "onWindowFocusChanged: height="+height);
            }
        });
    }

方法四

手动调用view.measure 进行measure得到view的宽高.方法较复杂,此处不表

猜你喜欢

转载自www.cnblogs.com/lanlengran/p/9790461.html