使用ListView 顯示數(shù)據(jù)
作者:佚名
在Android中,ListView是用來顯示一個(gè)列表的控件。每一行列表都是一個(gè)獨(dú)立的元素。這種控件既可以方便的顯示從系統(tǒng)中其他應(yīng)用讀取出來的數(shù)據(jù),也可獨(dú)立的為各行元素設(shè)置監(jiān)聽器。
效果圖
1、先定義item
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- <TextView
- android:layout_width="80dip"
- android:layout_height="wrap_content"
- android:id="@+id/personid"
- />
- <TextView
- android:layout_width="100dip"
- android:layout_height="wrap_content"
- android:id="@+id/name"
- />
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/amount"
- />
- </LinearLayout>
2、通過適配器把數(shù)據(jù)綁定到listview中,點(diǎn)擊某一行數(shù)據(jù)顯示編號(hào)
方式一:
- List<HashMap<String, Object>> data=new ArrayList<HashMap<String,Object>>();
- for(Person person :persons){
- HashMap<String, Object> hashMap=new HashMap<String, Object>();
- hashMap.put("id", person.getPersonId());
- hashMap.put("name", person.getName());
- hashMap.put("amount", person.getAmount());
- data.add(hashMap);
- }
- SimpleAdapter adapter=new SimpleAdapter(this,data,R.layout.item,new String[]{"id","name","amount"},new int[]{R.id.personid,R.id.name,R.id.amount}); listView.setAdapter(adapter);
- listView.setOnItemClickListener(new OnItemClickListener(){
- @Override
- public void onItemClick(AdapterView<?> parent, View view,
- int position, long id) {
- ListView myListView=(ListView)parent;
- HashMap<String, Object> item=(HashMap<String, Object>)myListView.getItemAtPosition(position);
- Toast.makeText(DBActivity.this, item.get("id").toString() , Toast.LENGTH_SHORT).show();
- }
- }
- );
方式二:用游標(biāo)的方式
- Cursor cursor=personService.getCursor(0, 15); //要求字段中要有_id 設(shè)計(jì)表的時(shí)候的主鍵為_id
- SimpleCursorAdapter cursorAdapter=new SimpleCursorAdapter(this,R.layout.item,cursor,new String[]{"_id","name","amount"},new int[]{R.id.personid,R.id.name,R.id.amount});
- listView.setAdapter(cursorAdapter);
- listView.setOnItemClickListener(new OnItemClickListener(){
- /**
- * parent當(dāng)前所點(diǎn)擊的listview對(duì)象
- * view當(dāng)前所點(diǎn)擊的條目
- */
- @Override
- public void onItemClick(AdapterView<?> parent, View view,
- int position, long id) {
- ListView myListView=(ListView)parent;
- Cursor data=(Cursor)myListView.getItemAtPosition(position);//根據(jù)位置移動(dòng)游標(biāo)
- int m=data.getInt(data.getColumnIndex("_id"));
- Toast.makeText(DBActivity.this, String.valueOf(m) , Toast.LENGTH_SHORT).show();
- }
- }
- );
【編輯推薦】
SQL Server與Oracle數(shù)據(jù)庫鏡像對(duì)比
責(zé)任編輯:zhaolei
來源:
網(wǎng)絡(luò)轉(zhuǎn)載