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

一個難住三年經驗工程師的 bug:addView 之後 scaleType 失效

編輯:關於 Android 程式設計

晚上九點多,一位合作夥伴發來一段代碼,說折騰了很久。需求很常見:圖片選擇器選完圖後把圖顯示到界面上,類似微信發圖。由於相機照片的長寬各不相同,為了排版統一,一般都會把 ImageView 的 scaleType 設為 centerCrop。

問題是:設了之後完全沒有效果。

先看對比(左為理想效果,右為實際效果):

復現結構

父布局是一個容器:

<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 的布局文件寫得沒毛病,寬高 30dp、scaleType 為 centerCrop:

<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" />

然後通過 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 container = (LinearLayout) findViewById(R.id.images_container);
    container.addView(image);
}

結果就是右圖,scaleType 形同虛設。

對照組

如果把 ImageView 直接寫在布局裡,代碼改成 findViewById:

<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>
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageResource(R.drawable.beni);

效果就完全正常。差別只在於一個走 inflate + addView,一個走 findViewById。

根因:LayoutParams 被丟掉了

看 ViewGroup.addView 的源碼:

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

關鍵在於:當 inflate 時傳入的 root 為 null、attachToRoot 為 false 時,生成的 View 拿不到父容器類型對應的 LayoutParams,child.getLayoutParams() 返回 null。此時 addView 會退回到 generateDefaultLayoutParams(),也就是 WRAP_CONTENT、WRAP_CONTENT。

可以打一行日志驗證:

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

於是 XML 裡精心寫好的 30dp × 30dp 被徹底忽略,ImageView 按 wrap_content 撐滿可用空間,比例完全失真,centerCrop 自然看不出裁剪效果。

注意結論的準確表述:失效的是寬高,不是 scaleType。scaleType 一直在生效,只是它作用的邊界已經不是 30dp 見方了。

修復

addView 之前手動補上 LayoutParams 即可:

@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);

    image.setImageResource(R.drawable.beni);

    Log.d("zzzzz", "" + image.getLayoutParams());   // 不再是 null
    LinearLayout container = (LinearLayout) findViewById(R.id.images_container);
    container.addView(image);
}

更規範的寫法是 inflate 時把真實父容器傳進去、attachToRoot 傳 false,讓框架自動生成正確類型的 LayoutParams:

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

這樣 inflate 內部會調用 generateLayoutParams(attrs),XML 中的 30dp 就被完整保留下來。

小結

這類問題的根源往往不是 API 不熟悉,而是對框架行為缺少驗證習慣。遇到「XML 寫了屬性卻不生效」的情況,排查順序建議是:先打印 getLayoutParams 確認是否為 null → 再看父容器類型 → 最後才懷疑屬性本身。另外也再次說明,框架層出不窮,但讀懂源碼、動手驗證的能力才是判斷問題的底氣。

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