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

Android 動態添加布局:用 inflate 逐項堆疊畫面

編輯:關於 Android 程式設計

做專案時遇到 ScrollView 與 ListView 混用的問題,會導致滑動手勢互相搶奪。解法之一是手動計算 ListView 高度(另見「在 ScrollView 中嵌套 ListView」)。但在這個專案裡,ScrollView 裡要放的是兩個 ListView,麻煩程度又上了一層。

與其繼續跟 ListView 的高度計算纏鬥,我換了另一條路:把其中一個 ListView 改成動態加載布局的方式實作。操作手感與 ListView 差不多,但不需要 Adapter。

子布局

<?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"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/action_settings"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" />
</LinearLayout>

顯示布局

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <LinearLayout
            android:id="@+id/lay"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

    <Button
        android:id="@+id/btn_add"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="click_add"
        android:text="@string/app_name" />
</LinearLayout>

這裡的結構是刻意的:ScrollView 裡面只放一個空的 LinearLayout 作為容器,所有內容都靠程式碼動態塞進去。因為容器本身是 LinearLayout,高度會隨子元件自然撐開,完全不需要手動計算。

程式碼實作

public class MainActivity extends Activity {

    private LinearLayout lay;
    private LinearLayout item;
    private ImageView img;
    private TextView txt;

    private final int[] pic = {
            R.drawable.ic_launcher, R.drawable.maps,
            R.drawable.appstore, R.drawable.calculator, R.drawable.camera };

    private final String[] str = {"1", "2", "3", "4", "5"};
    private int time = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lay = findViewById(R.id.lay);

        findViewById(R.id.btn_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inflateAndFind();
            }
        });
    }

    private void inflateAndFind() {
        // 每次呼叫都 inflate 一份新的子布局
        item = (LinearLayout) View.inflate(getBaseContext(), R.layout.item, null);
        img = item.findViewById(R.id.img);
        txt = item.findViewById(R.id.txt);

        if (time < pic.length) {
            img.setImageResource(pic[time]);
            txt.setText(str[time]);
            lay.addView(item);            // 加到容器底端
        } else {
            time = 0;                     // 到頭就重新開始
        }
        time++;
    }
}

程式邏輯說明

核心就是 inflate 這個方法。在 Android 裡它常被戲稱為「打氣筒」——把一個 XML 布局檔案吹成實際的 View 物件樹。呼叫一次就得到一份全新的 View,因此每按一次按鈕就多一筆資料,彼此獨立、互不影響。

流程是:inflate 出 item → 在 item 內部 findViewById 取得子元件 → 設定資料 → addView 掛到容器上。這裡的 findViewById 必須對 item 呼叫,而不是對 Activity 呼叫,否則拿到的是布局範本中的那一份,而不是新吹出來的實例。

這個做法的限制

動態 inflate 適合項目數量少的情況,但用在大量資料上會有明顯問題,必須說明清楚。

沒有重用機制。每次 inflate 都會配置一整棵 View 樹,項目上百之後記憶體與效能都會惡化。ListView 之所以有 Adapter,正是為了解决这个问题。

無法局部更新。要改第 50 筆的內容,得自己保存對那個 item 的參考並操作它,資料與 View 的對應關係要自己維護。

item 也是成員變數時會出問題。範例把 item、img、txt 宣告成成員變數,在單執行緒、一次一筆的情境下能運作,但若同時有多筆,這些參考會互相覆蓋。這裡應該改為區域變數。

更根本的建議。如果這個版面是「上方一段固定內容 + 下方一長串清單」,最乾淨的解法是只用一個 ListView,把上方那段固定內容做成 listType 之一(透過 getItemViewType 區分),或直接把 headerView 掛上去。這樣只有一個捲動容器、重用機制正常、手勢不衝突,也不必動態 inflate。ScrollView 裡放 ListView 之所以麻煩,本質上就是兩個都想管捲動的元件硬湊在一起。若清單項目本來就固定且極少(例如三五筆設定項),那麼用本文的動態 inflate 反而最直觀,不必引入 Adapter 的額外複雜度。

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