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);
}
}
mData,再 notifyDataSetChanged()。addAll() 批次新增後一次 notify,或改用 RecyclerView + DiffUtil 獲得局部刷新動畫。RecyclerView + ListAdapter,支援動畫、穩定 ID、分頁載入。// Adapter 繼承 ListAdapter- ,提交列表自動計算差異
adapter.submitList(newList); // 內部自動執行 DiffUtil、局部刷新