1. 使用流程
2. ArrayAdapter
new ArrayAdapter<?>(context, textViewResourceId, objects)
context:上下文
textViewResourceId:列表项的布局文件id
objects:数据源(数组或集合)
public class MainActivity extends Activity {
private ListView myListView;
private ArrayAdapter<String>arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//新建数据源
String[] data = {"初探ListView","初探ListView","初探ListView","初探ListView"};
//新建适配器并绑定数据源
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
//设置适配器
myListView = (ListView) findViewById(R.id.myListView);
myListView.setAdapter(arrayAdapter);
}
}
3. SimpleAdapter
new SimpleAdapter(context, data, resource, from, to)
context:上下文
data:List extends Map
resource:列表项的布局文件id
from:Map中的键名
to:列表项的布局文件中的组件id
public class MainActivity extends Activity {
private ListView myListView;
private SimpleAdapter simpleAdapter;
private List<Map<String, Object>> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//新建数据源
data = new ArrayList<Map<String, Object>>();
for (int i = 0; i < 20; i++) {
Map<String, Object>map = new HashMap<String, Object>();
map.put("img", R.mipmap.ic_launcher);
map.put("text", "初识simpleAdapter");
data.add(map);
}
//新建适配器并绑定数据源
simpleAdapter = new SimpleAdapter(this, getData(), R.layout.item, new String[]{"img", "text"}, new int[]{R.id.img, R.id.text});
//设置适配器
myListView = (ListView) findViewById(R.id.myListView);
myListView.setAdapter(simpleAdapter);
}
}