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

初始化時取得布局寬高:RelativeLayout 的 LayoutParams 陷阱

編輯:關於 Android 程式設計

前一篇談過如何在 onCreate 階段取得尚未顯示的 View 寬高——呼叫 view.measure(0, 0),再用 getMeasuredWidth() 與 getMeasuredHeight() 取值。今天想沿用這招做一個類似的下拉效果,給 ListView 加一個頭部視圖,卻在 RelativeLayout 上翻了車。

簡化後的頭部布局

headview.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView android:id="@+id/arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/information_top" />
</RelativeLayout>

初始化時照著上次的思路寫:

private LayoutInflater inflater;
private View headView;
private int headViewWidth;
private int headViewHeight;

inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
headView = inflater.inflate(R.layout.headview, null);
headView.measure(0, 0);
headViewWidth = headView.getMeasuredWidth();
headViewHeight = headView.getMeasuredHeight();
Log.i(TAG, "headViewWidth-->" + headViewWidth + " headViewHeight-->" + headViewHeight);
addHeaderView(headView);

結果程式直接崩潰。

說好的一行 measure 就能拿到寬高呢?怎麼報了空指針?把外層換成 LinearLayout 試試:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView android:id="@+id/arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/information_top" />
</LinearLayout>

竟然就好了,寬高也順利取到:

繼續追:問題出在哪個布局

為了簡化問題,沿著上次的思路,新增一個 viewgroup_relativelayout.xml,只把外層換成 RelativeLayout,其他不動:

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

    <View android:layout_width="50dp"
        android:layout_height="50dp" />
</RelativeLayout>

結果很整齊:View、TextView、LinearLayout 都正常,只有 RelativeLayout 掛掉。剛開始確實有點惱火,但轉念一想,解決問題的過程本身就是水平提升的過程,於是打起精神繼續查。

對比下來,出錯的一定是 RelativeLayout 的 onMeasure,空指針異常應該就定位在這裡。遺憾的是這個方法兩百多行,牽扯大量成員變數與子方法,硬讀很累。網上搜了一輪,找到一種說法:

使用 Inflater 渲染時,如果沒有為它指定父容器,渲染器不會去解析 width / height 屬性,就會導致空指針異常。
解法:先 view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) 指定寬高,再呼叫 measure。

這個說法確實能解決問題,但它沒解釋清楚:為什麼 LinearLayout 沒事,RelativeLayout 就出事?那就只能自己讀源碼了。

源碼中的答案

帶著「很可能是 onMeasure 裡直接用了 mLayoutParams,而它此時為 null」的假設,在 RelativeLayout(4.2 源碼)中所有出現 mLayoutParams 的位置下斷點:

// 493 行
if (mLayoutParams.width >= 0) {
    width = Math.max(width, mLayoutParams.width);
}

// 523 行
if (mLayoutParams.height >= 0) {
    height = Math.max(height, mLayoutParams.height);
}

斷言成立,mLayoutParams 確實是 null。

問題至此清楚了:用 inflate(R.layout.headview, null) 加載布局時,父容器傳入 null,因此外層 RelativeLayout 的 LayoutParams 沒有被賦值;偏偏 RelativeLayout 在 onMeasure 中沒有做 null 檢查,直接讀取 mLayoutParams.width / height,於是空指針。這個人為來看更像是一個 framework 層面的 bug。

解決方案

方法一:加載時帶上父容器。只要傳入真實的 ViewGroup,布局參數就會被正確解析:

headView = inflater.inflate(R.layout.viewgroup_relativelayout,
        (ViewGroup) findViewById(R.id.mainLayout), false);

方法二:手動補上布局參數。

ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);

順帶修正上次那個 measureView 方法。它雖然判斷了 lp 是否為 null,卻只 new 了一個對象而沒塞回去,等於白做,必須補上 setLayoutParams:

private void measureView(View child) {
    ViewGroup.LayoutParams lp = child.getLayoutParams();
    if (lp == null) {
        lp = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        child.setLayoutParams(lp);   // 這一句不能省
    }
    int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, lp.width);
    int childHeightSpec;
    if (lp.height > 0) {
        childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
    } else {
        childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    }
    child.measure(childWidthSpec, childHeightSpec);
}

回到 ListView 加頭部視圖

現在原來的問題很好解,兩條路:

路徑一:把 RelativeLayout 換成 LinearLayout。

路徑二:保留 RelativeLayout,用 inflate 的第三個參數帶上父容器:

inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
headView = inflater.inflate(R.layout.headview, this, false);
headView.measure(0, 0);   // 也可以換成 measureView(headView)
headViewWidth = headView.getMeasuredWidth();
headViewHeight = headView.getMeasuredHeight();
Log.i(TAG, "headViewWidth-->" + headViewWidth + " headViewHeight-->" + headViewHeight);
addHeaderView(headView);

但如果堅持用 inflate(R.layout.headview, null) 再搭配 measureView,程式依然會崩:

inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
headView = inflater.inflate(R.layout.headview, null);
measureView(headView);
headViewWidth = headView.getMeasuredWidth();
headViewHeight = headView.getMeasuredHeight();
addHeaderView(headView);

好消息是這次不再是空指針,而是型別轉換異常——因為 ListView 要求 LayoutParams 必須是 AbsListView.LayoutParams。改掉就好:

lp = new AbsListView.LayoutParams(
        AbsListView.LayoutParams.FILL_PARENT,
        AbsListView.LayoutParams.WRAP_CONTENT);

再跑一次,大功告成。

順手解決另一個老問題

把 ListView 塞進 ScrollView 時,它的高度常常顯示不全,只露出部分內容。常見解法是遍歷每個 item 手動累加高度,再回寫 LayoutParams:

private void setListViewHeight(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        return;
    }
    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + listView.getDividerHeight() * (listAdapter.getCount() - 1);
    listView.setLayoutParams(params);
}

想想看,如果這時候每個 item 的頂層是 RelativeLayout,又沒帶父容器、沒補 LayoutParams,同樣會在 measure 時爆炸。

結論

需要主動測量布局寬高時,請對 RelativeLayout 多一分戒心。核心規則只有兩條:inflate 時盡量傳入真實的父容器並把 attachToRoot 設為 false;如果一定要傳 null,就記得自己把 LayoutParams 補上,而且型別要與目標父容器匹配。

這些坑有人寫一輩子 App 都碰不到,也不影響做出好產品;但我認為任何問題都能磨練解決問題的能力,都有助於學習。

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