萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android ListView 動態新增項目完整範例:關鍵在 notifyDataSetChanged()

核心概念

ListView 配合 BaseAdapter 時,資料源變更後**必須**呼叫 adapter.notifyDataSetChanged() 通知 UI 重繪。常見錯誤:在 getView() 內呼叫、忘記呼叫、或資料結構未同步更新。

完整可運行範例

1. 佈局檔:res/layout/activity_dynamic_list.xml

<?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="vertical">

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:cacheColorHint="#00000000" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="16dp">

        <EditText
            android:id="@+id/et_new_item"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="輸入新項目"
            android:textSize="18sp" />

        <ImageButton
            android:id="@+id/btn_add"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:src="@android:drawable/ic_menu_add"
            android:contentDescription="新增" />
    </LinearLayout>
</LinearLayout>

2. 列表項佈局:res/layout/list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/tv_item_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:textSize="18sp"
    android:textColor="#333" />

3. Activity 代碼

public class DynamicListActivity extends ListActivity {

    private static final String KEY_TEXT = "text";
    private final List<Map<String, String>> mData = new ArrayList<>();
    private SimpleAdapter mAdapter;
    private EditText mInput;

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

        mInput = findViewById(R.id.et_new_item);
        ImageButton btnAdd = findViewById(R.id.btn_add);

        // 建立 Adapter:資料來源 mData、項佈局、對應鍵值
        mAdapter = new SimpleAdapter(this, mData,
                R.layout.list_item,
                new String[]{KEY_TEXT},
                new int[]{R.id.tv_item_text});
        setListAdapter(mAdapter);

        btnAdd.setOnClickListener(v -> addItem());
    }

    private void addItem() {
        String text = mInput.getText().toString().trim();
        if (text.isEmpty()) return;

        // 1. 更新資料源
        Map<String, String> item = new HashMap<>();
        item.put(KEY_TEXT, text);
        mData.add(item);

        // 2. 關鍵:通知 Adapter 資料已變更
        mAdapter.notifyDataSetChanged();

        // 3. 清空輸入框並滾動到最新項
        mInput.setText("");
        getListView().smoothScrollToPosition(mData.size() - 1);
    }
}

關鍵點總結

  1. 資料源與 Adapter 同步:先修改 mData,再 notifyDataSetChanged()。
  2. 不要在 getView() 呼叫 notify:會導致無限循環重繪。
  3. 大量資料插入:建議使用 addAll() 批次新增後一次 notify,或改用 RecyclerView + DiffUtil 獲得局部刷新動畫。
  4. 現代替代:新專案優先採用 RecyclerView + ListAdapter,支援動畫、穩定 ID、分頁載入。

進階:RecyclerView 版本片段

// Adapter 繼承 ListAdapter,提交列表自動計算差異
adapter.submitList(newList); // 內部自動執行 DiffUtil、局部刷新
copyright © 萬盛學電腦網 all rights reserved