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







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章