ArrayAdapter學習總結

  1. ArrayAdapter常用6個構造方法:
android.widget.ArrayAdapter<T>
ArrayAdapter(Context context, int textViewResourceId)
ArrayAdapter(Context context, int resource, int textViewResourceId)
ArrayAdapter(Context context, int textViewResourceId, T[] objects)
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)        
ArrayAdapter(Context context, int textViewResourceId, List<T> objects)
ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects)
  1. 參數說明:
  • context:The current context。(傳遞Context對象,一般爲this
  • resource(The id of the TextView within the layout resource to be populated):該佈局資源在res/layout/xxx.xml中定義後會自動在R.java文件中生成對應的ID,然後利用R.layout.xxx調用即可,也可以使用系統已定義好的佈局文件,比如:
android.R.layout.simple_list_item_1
android.R.layout.simple_expandable_list_item_1

注意:佈局文件必須是關於TextView組件的XML文件(也可以TextView類的子類組件,如Button, CheckedTextView, Chronometer, DigitalClock, EditText, TextClock都是TextView的子類),列表項的每個條項都是按照這個TextView組件進行顯示。

  • textViewResourceId: 對應的是resource佈局文件中TextView組件的ID;
  • objects (The objects to represent in the ListView):數組或者List集合,用於爲多個列表項提供數據。

從中可知:
textViewResourceId用於控制每個列表項的TextView組件(控制佈局形式顯示風格),
objects(數組或者List集合)爲每個列表項的TextView組件提供顯示數據。
數組或者List集合有多少個元素,將會生成多少個列表項。

  1. resourcetextViewResourceId參數區別:

一般來說,resource對應的是佈局XML資源文件,而textViewResourceId指的是XML資源文件中textView組件的ID

常見錯誤ArrayAdapter requires the resource ID to be a TextView
ArrayAdapter初始化時,參數

ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item, objects);

顯然不符合上面的ArrayAdapter6個構造方法

ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item,R.id.textView ,objects);

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章