现在的位置: 首页 > 综合 > 正文

android笔记 SimpleAdapter的构造方法说明

2014年01月16日 ⁄ 综合 ⁄ 共 1998字 ⁄ 字号 评论关闭

将ListView和SimpleAdapter配合使用,对于List中的每行内容,实际是由很多记录组成的,比如一行内,有ID,name,sex等属性,它们一起构成一条记录。

因此,需要用Map来对应List中的一行,Map中的一个键值对,对应于一行中的一个属性,通过一个键名,可以得到一个值,这个值不一定是String,还可以是其他类型的数据。

SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

SimpleAdapter的构造方法有5个参数。

第1个是上下文对象,第3个是每一行数据的布局文件。

第2个是保存有每一行数据的Map构成的List对象,也就是说,每一行数据里的每一个属性都由它的名字和它的值构成一个键值对,每一行的多个键值对构成这一行的一个Map对象,再由多行的多个Map对象够成一个List对象。

第3个String数组是键的集合,第4个int数组是布局文件中控件ID的集合,也就是说,从String数组里的键名去找到值,然后将这个值赋给在int数组里位置对应的控件。

因此,对于from,如果from里出现的键名是Map里没有的,将不会有数据显示,因为通过这个错误的键找不到值。form数组里的字符串,一定要是Map里的键的值。

package tjj.ListViewTest;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class ListViewTestActivity extends ListActivity
{
		ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

		/** Called when the activity is first created. */
		@Override
		public void onCreate(Bundle savedInstanceState)
		{
				super.onCreate(savedInstanceState);
				setContentView(R.layout.main);
				HashMap<String, String> map1 = new HashMap<String, String>();
				HashMap<String, String> map2 = new HashMap<String, String>();
				HashMap<String, String> map3 = new HashMap<String, String>();

				map1.put("user_name", "tjj");
				map1.put("user_good", "programing");

				map2.put("user_name", "hello");
				map2.put("user_good", "sport");

				map3.put("user_name", "world");
				map3.put("user_good", "loving");

				list.add(map1);
				list.add(map2);
				list.add(map3);

				SimpleAdapter listAdapter = new SimpleAdapter(this, 
								list, 
								R.layout.user, 
								new String[] { "user_name", "user_good" }, 
								new int[] { R.id.user_name, R.id.user_ip });

				setListAdapter(listAdapter);
		}

		@Override
		protected void onListItemClick(ListView l, View v, int position, long id)
		{
				System.out.println(position);
				HashMap<String, String> map = list.get(position);
				String name = map.get("user_name");
				String good = map.get("user_good");
				Toast.makeText(this, name + ":" + good, Toast.LENGTH_SHORT).show();
				super.onListItemClick(l, v, position, id);
		}
}

抱歉!评论已关闭.