我需要显示
类别
从ListActivity。我的数据源是类型为的ArrayList
Category
它正在实现android可打包接口。结构在底部。它有身份证和头衔
我需要将标题显示为列表文本,单击列表项时,我需要获取id以进行进一步处理
通过迭代category ArrayList并使用
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.rowlayout, R.id.label, names));
但是如果使用这种方法,我只会在点击时得到类别的标题,而不是id。
是否可以直接使用对象的ArrayList作为数据源?
public class CategoryList extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Intent t = new Intent(this, ParsingWebXML.class);
startActivityForResult(t,1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 1 && resultCode == RESULT_CANCELED){
finish();
} else {
createCategoryList(data);
}
}
private void createCategoryList(Intent data) {
ArrayList<Category> categories = null;
try {
categories = data.getParcelableArrayListExtra("categoryList");
Iterator<Category> itr = categories.iterator();
String[] names = new String[categories.size()];
int i=0;
while (itr.hasNext()) {
Category c = itr.next();
names[i++] = c.getTitle();
}
this.setListAdapter(new ArrayAdapter<Category>(this, R.layout.rowlayout, R.id.label, categories));
// String[] names = new String[] { "Sports", "Mediacal", "Computers" };
// this.setListAdapter(new ArrayAdapter<String>(this, R.layout.rowlayout, R.id.label, names));
} catch (Exception e) {
// TODO: handle exception
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
if(keyword=="Categories"){
Intent cat = new Intent(this, CategoryActivity.class);
startActivity(cat);
//Toast.makeText(this, keyword, Toast.LENGTH_LONG).show();
} else {
Intent cat = new Intent(this, CategoryActivity.class);
startActivity(cat);
}
}
}
类别.java
public class Category implements Parcelable {
private int id;
private String title;
public Category() {
}
public Category(Parcel source) {
id = source.readInt();
title = source.readString();
}
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public int getId() {
return this.id;
}
public String getTitle() {
return this.title;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(title);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
@Override
public Category createFromParcel(Parcel source) {
return new Category(source);
}
@Override
public Category[] newArray(int size) {
return new Category[size];
// TODO Auto-generated method stub
}
};
}