ListView使用SimpleAdapter显示数据

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();	
			}
		});
	}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值