ListView使用SimpleAdapter显示数据

来源:互联网 发布:中国消防网站的域名是 编辑:程序博客网 时间:2024/05/15 12:01

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>>();@Overrideprotected 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++) {//存入mapMap<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的itemlv.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {Toast.makeText(MainActivity.this, "点击了第"+arg2, Toast.LENGTH_SHORT).show();}});}






1 0
原创粉丝点击