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

深入剖析 ListView 動態增刪數據項的經典陷阱

編輯:關於 Android 程式設計

在 ListView 等 AdapterView 上動態添加、刪除列表項時,稍不留神就會踩坑。本文就帶大家一起揭開這個經典陷阱的真相。

定義 array 資源

先準備一份字符串數組作為列表的加載內容:

 <resources> <string name="app_name">MyListView</string> <string-array name="language"> <item>Java</item> <item>C</item> <item>C++</item> <item>PHP</item> </string-array>

布局文件

為了讓編輯框與按鈕始終固定在底部,把 ListView 的 layout_weight 設為 1:

 <?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="fill_parent" android:layout_height="0dip" android:layout_weight="1" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <EditText android:id="@+id/addLangEdit" android:layout_width="200px" android:layout_height="wrap_content" /> <Button android:id="@+id/addButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="添加" /> </LinearLayout> </LinearLayout>

Activity 代碼

 public class MyListView extends ListActivity { private ArrayAdapter<CharSequence> mAdapter; private ListView mListView; private EditText mLanguageText; private Button mAddButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mylist1); mListView = getListView(); mLanguageText = (EditText) findViewById(R.id.addLangEdit); mAddButton = (Button) findViewById(R.id.addButton); mAdapter = ArrayAdapter.createFromResource(this, R.array.language, android.R.layout.simple_list_item_1); mListView.setAdapter(mAdapter); mAddButton.setOnClickListener(mOnClickListener); } private OnClickListener mOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { String text = mLanguageText.getText().toString(); if(null == text || "".equals(text.trim())) { Toast.makeText(MyListView.this, "輸入不能為空", Toast.LENGTH_SHORT).show(); }else { mAdapter.add(text); mAdapter.notifyDataSetChanged(); mLanguageText.setText(""); } } }; }

界面能正常顯示,但每次點擊「添加」卻拋出 java.lang.UnsupportedOperationException。明明按 API 文檔,add、remove 等方法本應能在運行時增刪列表項,問題究竟出在哪?

查閱資料後找到線索:要動態改變列表大小,必須使用可變長度的 List(如 ArrayList),而不能用固定長度的數組,否則就會拋出 UnsupportedOperationException。由於我們從資源文件加載內容,很自然地想到用 ArrayAdapter.createFromResource(...) 來構造 adapter,而這個方法恰恰導致了問題。我們再深入源碼一探究竟。

 public class ArrayAdapter<T> extends BaseAdapter implements Filterable { private List<T> mObjects; public ArrayAdapter(Context context, int textViewResourceId, List<T> objects) { init(context, textViewResourceId, 0, objects); } public ArrayAdapter(Context context, int textViewResourceId, T[] objects) { // 注意這裡的 Arrays.asList(...) 方法!!! init(context, textViewResourceId, 0, Arrays.asList(objects)); } public static ArrayAdapter<CharSequence> createFromResource(Context context, int textArrayResId, int textViewResId) { CharSequence[] strings = context.getResources().getTextArray(textArrayResId); return new ArrayAdapter<CharSequence>(context, textViewResId, strings); } private void init(Context context, int resource, int textViewResourceId, List<T> objects) { mContext = context; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mResource = mDropDownResource = resource; mObjects = objects; mFieldId = textViewResourceId; } public void add(T object) { if (mOriginalValues != null) { synchronized (mLock) { mOriginalValues.add(object); if (mNotifyOnChange) notifyDataSetChanged(); } } else { mObjects.add(object); // 若該 mObjects 為固定長度 List,此處將拋異常!!! if (mNotifyOnChange) notifyDataSetChanged(); } } }

從源碼不難看出,ArrayAdapter 並未單獨維護數組,而是統一轉換為 List 存進 mObjects。createFromResource(...) 內部調用了 ArrayAdapter(Context, int, T[]) 構造方法,而該方法使用了 Arrays 的靜態方法 asList(...) 把數組轉為 List。熟悉 Java 的朋友都知道,Arrays.asList(...) 返回的並不是 java.util.ArrayList,而是 Arrays 的內部類,這個 List 不支持增刪操作,一旦調用 add 就會拋出 UnsupportedOperationException!至此,真相終於水落石出。

最終解決方案

只需稍微改動,把數據包一層真正的 ArrayList 即可:

 public class MyListView extends ListActivity { private ArrayAdapter<CharSequence> mAdapter; private ListView mListView; private EditText mLanguageText; private Button mAddButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mylist1); mListView = getListView(); mLanguageText = (EditText) findViewById(R.id.addLangEdit); mAddButton = (Button) findViewById(R.id.addButton); // 用真正的 ArrayList 包裹 List<CharSequence> objects = new ArrayList<CharSequence>(Arrays.asList(getResources().getTextArray(R.array.language))); mAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1, objects); mListView.setAdapter(mAdapter); mAddButton.setOnClickListener(mOnClickListener); } private OnClickListener mOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { String text = mLanguageText.getText().toString(); if(null == text || "".equals(text.trim())) { Toast.makeText(MyListView.this, "輸入不能為空", Toast.LENGTH_SHORT).show(); }else { mAdapter.add(text); mAdapter.notifyDataSetChanged(); mLanguageText.setText(""); } } }; }

以上就是關於 Android ListView 動態增刪數據項的深入分析,希望對大家的學習有所幫助。

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