美文网首页Android
获取View宽高的四种方式

获取View宽高的四种方式

作者: 合拍v | 来源:发表于2021-01-27 21:52 被阅读0次

      一开始写Android获取view的宽高的时候,经常会直接调用一些方法,实际获得的宽高都是0。后来才知道是因为View宽高的测量与Activity的生命周期并不是同步的,调用函数的时候很可能View的measure函数还没有执行完,下面介绍四种获取View宽高的方式。

    1. onWindowFocusChanged
    @Override
      public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
          int width = view.getMeasuredWidth();
          int height = view.getMeasuredHeight();
        }
      }
    
    1. view.post(runnable)
    @Override
      protected void onStart() {
        super.onStart();
        view.post(new Runnable() {
          @Override
          public void run() {
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
          }
        });
      }
    
    1. ViewTreeObserver
    @Override
      protected void onStart() {
        super.onStart();
        ViewTreeObserver observer = view.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
          @SuppressWarnings(value = "deprecation")
          @Override
          public void onGlobalLayout() {
            view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
          }
        });
      }
    
    1. view.measure(int widthMeasureSpec, int heightMeasureSpec)
      这种方法手动测量View的宽高,需要分三种情况:
       (1) View宽高为具体的值w, h
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY);
        view.measure(widthMeasureSpec, heightMeasureSpec);
    

      (2) 设置为wrap_content

        int widthMeasureSpec =
            View.MeasureSpec.makeMeasureSpec(((1 << 30) - 1), View.MeasureSpec.AT_MOST);
        int heightMeasureSpec =
            View.MeasureSpec.makeMeasureSpec(((1 << 30) - 1), View.MeasureSpec.AT_MOST);
        view.measure(widthMeasureSpec, heightMeasureSpec);
    

      (3)设置为match_parent时是不能测出具体的宽高的,因为获取不到parentSize。

    相关文章

      网友评论

        本文标题:获取View宽高的四种方式

        本文链接:https://www.haomeiwen.com/subject/ebhzzktx.html