Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 初級教程:如何在代碼中正確獲取控件的寬與高

編輯:關於 Android 開發

獲取 Android 控件寬高的三種方法與取捨

我們都知道,在 onCreate() 裡獲取控件的高度往往是 0,這是為什麼呢?先看一個簡單的自定義控件:

public class MyImageView extends ImageView {
    public MyImageView(Context context, AttributeSet attrs) { super(context, attrs); }
    public MyImageView(Context context) { super(context); }

    @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        System.out.println("onMeasure 我被調用了" + System.currentTimeMillis());
    }

    @Override protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        System.out.println("onDraw 我被調用了" + System.currentTimeMillis());
    }
}

佈局檔:

<com.test.MyImageView
    android:id="@+id/imageview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/test" />

測試 Activity 的 onCreate():

@Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    System.out.println("執行完畢.." + System.currentTimeMillis());
}

從輸出結果可以看到:等到 onCreate 執行完畢,我們定義的控件才被度量(measure)。所以在 onCreate 中透過 view.getHeight() 獲取的高度必然是 0——因為它自己還沒被度量,連它都不知道自己有多高,你自然拿不到正確尺寸。

既然問題存在,就得想辦法解決。網路上常見的三種方案如下:

// 方法一:手動調用 measure
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
imageView.measure(w, h);
int height = imageView.getMeasuredHeight();
int width = imageView.getMeasuredWidth();

// 方法二:OnPreDrawListener
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    public boolean onPreDraw() {
        int height = imageView.getMeasuredHeight();
        int width = imageView.getMeasuredWidth();
        return true;
    }
});

// 方法三:OnGlobalLayoutListener
ViewTreeObserver vto2 = imageView.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override public void onGlobalLayout() {
        imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        int height = imageView.getHeight();
        int width = imageView.getWidth();
    }
});

把 Activity 改成使用方法一後,輸出結果如下:

使用方法二時的結果:

方法三不再單獨測試,行為與方法二相同。

那麼方法二與方法三在執行上有何差異?我們在佈局中放一個 TextView 來記錄寬高:

<ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" >
    <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</ScrollView>

方法二的結果:

方法三的結果:

兩者的差異相信已不言自明。

總結:需要獲取控件寬高時該選哪個方法?

方法一:比其他兩個多了一次計算,也就是多調用了一次 onMeasure()。若目標控件的計算較耗時(如 ListView),不建議使用。

方法二:回調方法會被調用很多次,滑動 TextView 時仍會觸發,因此不建議使用。

方法三:相對更合適。

當然,實際應用時還是要根據具體場景來權衡選擇。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved