android:ListView使用总结 java程序员

ListView的实现要有一个数组和一个单行的布局文件,同时还要有一个适配器将数组和ListView关联起来

不同内容的ListView,相应的采用不同的适配器

Item为单行文本的ListView,可以使用ArrayAdapter

代码如下:

ListView lv=new ListView(this);
ArrayAdapter adapter=new Adapter(this,android.R.layout.simple_list_item_1,数组);
lv.setAdapter(adapter);
setContentView(lv);

如果Item有多个控件,那么可以使用SimpleAdapter

package com.example.listview1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		ListView lv=new ListView(this);
		SimpleAdapter adapter=new SimpleAdapter(this,getData(),R.layout.simple_layout,
				new String[]{"name","num","grade"},
				new int[]{R.id.name,R.id.num,R.id.grade});
		lv.setAdapter(adapter);
		setContentView(lv);
	}
	public List<Map<String,Object>> getData()
	{
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		Map map=new HashMap();
		map.put("name","student1");
		map.put("num", "num1");
		map.put("grade","grade1");
		list.add(map);
		map=new HashMap();
		map.put("name","student2");
		map.put("num", "num2");
		map.put("grade","grade2");
		list.add(map);
		map=new HashMap();
		map.put("name","student3");
		map.put("num", "num3");
		map.put("grade","grade3");
		list.add(map);
		return list;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

R.layout.simple_layout文件声明如下:

<?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="horizontal" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ></TextView>
    <TextView
        android:id="@+id/num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ></TextView>
    <TextView
        android:id="@+id/grade"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ></TextView>
</LinearLayout>

运行结果:



 


 

原文地址:https://www.cnblogs.com/java20130725/p/3215859.html