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

一個難倒「三年經驗」Android 工程師的 Bug:ImageView 的 scaleType 為什麼失效

編輯:關於 Android 開發

一個難倒「三年經驗」Android 工程師的 Bug

晚上九點多,合作的外包夥伴丟了一份工程給我,說有個「bug」折騰了很久搞不定,讓我幫忙看一眼。

場景很常見:做一個圖片選擇器,用戶選完圖之後要把圖片鋪到界面上預覽。參考微信發圖的思路,相機拍出來的照片長寬比例五花八門,為了讓排版統一,通常會把承載圖片的 ImageView 設成 centerCrop 或 center,靠系統幫我們裁切。

問題就在這裡:他把 scaleType 設上去之後,畫面一點變化都沒有,圖片照樣被拉伸變形。

先對比一下理想效果與實際效果(左為預期,右為實際):

共用的容器布局

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/images_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="10dp" />

</RelativeLayout>

出問題的 ImageView 寫法

<ImageView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/image_one"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:scaleType="centerCrop" />

然後在 Activity 裡動態 inflate 出來,再 addView 掛到容器上(為了敘述簡潔,示例代碼做了簡化,但現象完全一致):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);

    ImageView image = (ImageView) LayoutInflater.from(this)
            .inflate(R.layout.send_post_image, null, false);
    image.setImageResource(R.drawable.beni);

    LinearLayout imagesContainer = (LinearLayout) findViewById(R.id.images_container);
    imagesContainer.addView(image);
}

表面上看毫無破綻:用 inflate() 實例化一個 View,這個 View 的 XML 裡明確寫了 30dp × 30dp、明確寫了 centerCrop,最後掛進 LinearLayout。但跑出來就是右圖那個被拉變形的樣子。

對照組:findViewById 一切正常

你大概會有個印象——平時項目裡 ImageView 都是 findViewById 拿的,同樣的屬性卻從沒出過問題。沒錯,換一種寫法就正常。把 test.xml 改成把 ImageView 直接寫進容器:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/images_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="10dp">

        <ImageView
            android:id="@+id/image"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:scaleType="centerCrop" />

    </LinearLayout>

</RelativeLayout>

Java 側相應改成:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);

    ImageView image = (ImageView) findViewById(R.id.image);
    image.setImageResource(R.drawable.beni);
}

這回效果就是我們期待的裁切樣子。那為什麼走 addView() 就敗了?

答案:LayoutParams 根本沒被解析出來

關鍵在於:當你調用不帶 LayoutParams 的 addView() 時,系統會去讀取子 View 自己的 LayoutParams;而通過 inflate(id, null, false) 生成的 View,root 為 null,XML 上的 layout_width / layout_height 不會被解析並關聯到 LayoutParams 上,於是拿到的是 null。注意:scaleType 是 View 自身的屬性,它是生效的;失效的只有寬高。

把源碼貼出來看就很清楚:

/**
 * Adds a child view. If no layout parameters are already set on the child,
 * the default parameters for this ViewGroup are set on the child.
 */
public void addView(View child) {
    addView(child, -1);
}

public void addView(View child, int index) {
    if (child == null) {
        throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
    }
    LayoutParams params = child.getLayoutParams();
    if (params == null) {
        params = generateDefaultLayoutParams();
        if (params == null) {
            throw new IllegalArgumentException(
                "generateDefaultLayoutParams() cannot return null");
        }
    }
    addView(child, index, params);
}

protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}

想自己驗證,只要在示例代碼裡加一行日誌:

Log.d("zzzzz", "" + image.getLayoutParams());   // 輸出 null

既然 getLayoutParams() 返回 null,它就退散去問 generateDefaultLayoutParams(),而後者直接給了 WRAP_CONTENT × WRAP_CONTENT。控件被內容撐開,30dp 的限制自然不復存在,裁切也就無從談起。

那我想繼續用 addView 怎麼辦?

自己把寬高補上就行:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);

    ImageView image = (ImageView) LayoutInflater.from(this)
            .inflate(R.layout.send_post_image, null, false);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(50, 50); // 手動指定寬高
    image.setLayoutParams(lp);                                          // 掛上 LayoutParams

    image.setImageResource(R.drawable.beni);
    Log.d("zzzzz", "" + image.getLayoutParams());

    LinearLayout imagesContainer = (LinearLayout) findViewById(R.id.images_container);
    imagesContainer.addView(image);
}

另外一個更省事的做法是把容器當 root 傳進去:inflate(R.layout.send_post_image, imagesContainer, false),這樣 XML 裡的 layout_width / layout_height 就會被正常解析。

小結

這類問題之所以能困住人,往往不是因為知識點冷門,而是因為平時框架封裝得太好,我們很少有機會去追問「這個屬性到底是誰讀的」。源碼翻開只有十幾行,卻能省下一整晚。框架越來越多,能沉下來踏實讀幾行源碼的人反而越顯得稀缺。

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