本demo系列博客只提供代码,便于直接使用
原理参考此博客
- 包含listview的xml文件
<ListView
android:id="@+id/demo_listview" //改变这里
android:layout_width="match_parent"
android:layout_height="wrap_content">
- listview单个item的xml需要自定义
自定义
- 初始化listview代码
//假设这里的参数data为[{"titledata":"jdfiajf","authordata":"jdfosjof"},{...},...]
void initListView(JSONArray data) throws JSONException {
String[] itemNames=new String[]{"title","author"};
int[] itemIds=new int[]{R.id.item_title,R.id.item_author};//item的组件id
ArrayList<HashMap<String,Object>> listItem=new ArrayList<HashMap<String,Object>>();
for(int i=0;i<data.length();++i){
HashMap<String,Object> map=new HashMap<String,Object>();
JSONObject carddata=data.getJSONObject(i);
map.put("title",carddata.getString("titledata"));//这里必须和itemNames和data分别对应
map.put("author",carddata.getString("authordata"));
listItem.add(map);
}
SimpleAdapter mAdapter=new SimpleAdapter(this,listItem,R.layout.list_item,itemNames,itemIds);
pickListView.setAdapter(mAdapter);
}