您的位置:首页 > 其它

ListView使用SimpleAdapter显示数据

2017-02-06 13:32 411 查看
1、activity_main中加入控件Listview

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

2、创建lieview的item布局listview_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/tv"
android:text="数据"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="40dp" />

</LinearLayout>  这里就显示个文本
3、MainActivity代码:

private ListView lv;
private List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.lv);
//listview加入数据
init();

}
private void init() {
for (int i = 0; i <50; i++) {
//存入map
Map<String , Object> map=new HashMap<String, Object>();
map.put("name", "数据"+i);

//添加到集合中
list.add(map);
}
//SimpleAdapter适配器用法,第一个参数上下文,第二个:数据,第三个:listview中的布局界面,第四个:刚刚Map里面存的name,第五个:就是把第四个的name显示到哪一个控件上
SimpleAdapter sim=new SimpleAdapter(MainActivity.this, list, R.layout.listview_item, new String[]{"name"},new int[]{R.id.tv} );
lv.setAdapter(sim);
//判断点击了第几个listview的item
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {

Toast.makeText(MainActivity.this, "点击了第"+arg2, Toast.LENGTH_SHORT).show();
}
});
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐