您的位置:首页 > 其它

ListActivity和SimpleAdapter

2016-04-11 18:54 274 查看
今天写小程序时用Arrayadpter关联一个自定义Entpy类(类中有两个String类型)集合。

发现得到的是数据在内存中的位置。

于是就想找其他方式能满足所要实现功能

于是就找到了ListActivity和SimpleAdapter

ListActivity被一个Class类继承,


其实本身是不用setContentView,Android也会自动帮我们构造出一个全屏的列表。

SimpleAdapter是扩展性最好的适配器,可以定义各种你想要的布局,而且使用很方便

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

参数context:上下文

参数data:Map列表,列表要显示的数据,类型要与上面的一致,每条项目要与from中指定条目一致

参数resource:ListView单项布局文件的Id,这个布局就是你自定义的布局了,你想显示什么样子的布局都在这个布局中。这个布局中必须包括了to中定义的控件id

参数 from:一个被添加到Map上关联每一个项目列名称的列表,数组里面是列名称

参数 to:是一个int数组,数组里面的id是自定义布局中各个控件的id,需要与上面的from对应

public class Dianhuahaoma extends ListActivity{

List<Entpy> contactsList =new ArrayList<Entpy>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SimpleAdapter adapter = new SimpleAdapter(this, getData(),

                R.layout.phonenumber, new String[] { "name", "number" },

                new int[] { R.id.name, R.id.number });

        setListAdapter(adapter);

OnItemClickListener a=new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
};
//添加点击事件
getListView().setOnItemClickListener(a);

}

//这是练习(通过内容提供者来获得系统中联系人数据)
private List<Map<String, Object>> getData()
{
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
 
Cursor cursor=null;
try
{
//查询联系人数据
cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
Map<String, Object> map ;
while(cursor.moveToNext())
{
map = new HashMap<String, Object>();

//获取联系人姓名
String name=cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

//获取联系人手机号
String number=cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));

map.put("name", name);
       map.put("number", number);
       list.add(map);

}

}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(cursor!=null)
{
cursor.close();
}
}
 
 
 
return list;
}

4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: