ArrayAdapter(数组适配器)一般用于显示一行文本信息,
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);