本方法,采用继承ListActivity,来实现的,需要注意的是,在配置文件中ListView的ID书写方式@id/android:list
以及在对应的Activity中通过调用setListAdapter(adapter);实现数据填充;简化代码书写。
item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="10dp" android:paddingRight="10dp" android:paddingTop="1dp" android:paddingBottom="1dp" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/scoreId" android:layout_width="60dip" android:layout_height="30dip" android:textSize="10pt" android:singleLine="true"/> <TextView android:id="@+id/userName" android:layout_width="80dip" android:layout_height="30dip" android:textSize="10pt" android:singleLine="true"/> <TextView android:id="@+id/userScore" android:layout_width="80dip" android:layout_height="30dip" android:textSize="10pt" android:singleLine="true"/> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<LinearLayout
android:id="@+id/listLinearLayout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ListView
android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
public class ScoreListActivity extendsListActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scorelist);
ScoreDao scoreDao=new ScoreDao(ScoreListActivity.this);
List<UserScore> userScores=scoreDao.getAllScore();
ArrayList<HashMap<String,Object>> list=new ArrayList<HashMap<String,Object>>();
for (UserScore userScore : userScores) {
HashMap <String,Object> map=new HashMap <String,Object>();
map.put("scoreId", userScore.getId());
map.put("userName", userScore.getUserName());
map.put("userScore", userScore.getUserScore());
list.add(map);
}
SimpleAdapter adapter=new SimpleAdapter(ScoreListActivity.this,
list,R.layout.item, new String[]{"scoreId","userName","userScore"},
new int[]{R.id.scoreId,R.id.userName,R.id.userScore});
setListAdapter(adapter);
}
//重写ListActivity中的onListItemClick()方法
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
HashMap<String, Object> item = (HashMap<String, Object>)listView.getItemAtPosition(position);
//获取被选中行对应的ID
Object scoreId=item.get("scoreId");
Toast.makeText(ScoreListActivity.this,scoreId.toString(), Toast.LENGTH_LONG).show();
}
}