我創建了一個自定義ListView。列表中的每個項目都有一個imageView和兩個TextView。管理列表項ListView
的代碼是:
public class PersonalList extends ListActivity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] name= new String[] { "Mary", "Frank",
"John" };
String[] surname = new String[] { "Ballak", "Doe",
"Strip"" };
setContentView(R.layout.member_list);
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, name, surname);
setListAdapter(adapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
String name = (String) getListAdapter().getItem(position);
Toast.makeText(this, "selected item: "+name, Toast.LENGTH_LONG).show();
}
}
其中MySimpleArrayAdapter是:
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] name;
private final String[] surname;
public MySimpleArrayAdapter(Context context, String[] name, String[] surname)
{
super(context, R.layout.list_row, name);
this.context = context;
this.name= name;
this.surname = surname;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView nameView= (TextView) rowView.findViewById(R.id.label);
TextView surnameView= (TextView) rowView.findViewById(R.id.label1);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
nameView.setText(name[position]);
surnameView.setText(surname[position]);
return rowView;
}
}
調用從onListItemClick
以下代碼:
Toast.makeText(this, "selected item: "+name, Toast.LENGTH_LONG).show();
我獲得的第一個項目中烤麪包的消息像這樣:
"selected item: Mary"
如何才能獲得以下結果?
"selected item: Mary Ballak"
我強烈建議看Android的羅ain Guy [討論適配器和效率](http://www.google.com/events/io/2009/sessions/TurboChargeUiAndroidFast.html)的一些專業技巧,因爲我沒有使用ArrayAdapter的獨特方法擴展了BaseAdapter。 – Sam