android獲取view寬高的幾種方法 - ysl_longer

android獲取view寬高的幾種方法 - ysl_longer

在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());
    }
  }

發佈了6 篇原創文章 · 獲贊 6 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章