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)
- 參數說明:
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
集合有多少個元素,將會生成多少個列表項。
resource
和textViewResourceId
參數區別:
一般來說,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);
顯然不符合上面的ArrayAdapter
6個構造方法
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item,R.id.textView ,objects);