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

為 EditText 加入複合圖示:setCompoundDrawables 與 IntrinsicBounds 版本的差別

編輯:關於 Android 程式設計

要在 EditText 的左側放一個小圖示,用複合 Drawable 是最省事的做法,不需要額外排一層 LinearLayout。

基本用法

Bitmap bitmap = mWebView.getFavicon();
Drawable drawable = new BitmapDrawable(bitmap);
// edit.setCompoundDrawables(drawable, null, null, null);

drawable = this.getResources().getDrawable(R.drawable.history);
edit.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
edit.setText(cur_url);
// edit.setMaxLines(1);

兩個方法的關鍵差異

setCompoundDrawables 會嚴格按照 drawable.setBounds() 所設定的寬高來繪製,所以官方才會特別警告「The Drawables must already have had setBounds(Rect) called.」——不先呼叫就會拿到尺寸為 0 的圖,什麼都看不到。

setCompoundDrawablesWithIntrinsicBounds 則直接使用 Drawable 自身的固有尺寸,也就是透過 getIntrinsicWidth() 與 getIntrinsicHeight() 取得的值,因此文件寫的是「The Drawables' bounds will be set to their intrinsic bounds.」。從原始碼就能看得很清楚:

public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top,
        Drawable right, Drawable bottom) {

    if (left != null) {
        left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
    }
    if (right != null) {
        right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight());
    }
    if (top != null) {
        top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
    }
    if (bottom != null) {
        bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight());
    }
    setCompoundDrawables(left, top, right, bottom);
}

換句話說,setCompoundDrawablesWithIntrinsicBounds 只是幫你把 setBounds 這一步自動做掉了。實務上的選擇很單純:直接用資源 ID 或 Drawable 物件時,用 IntrinsicBounds 版本最方便;需要精確控制圖示顯示尺寸(例如想把一張大圖縮小顯示)時,才走 setBounds 加 setCompoundDrawables 的組合。此外,這個方法也有接受資源 ID 的重載版本 setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom),能省掉手動 getDrawable() 的麻煩。

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