[英]how to make a listview of objects in android and access the object fields by clicking listitems?
我在我的android應用程序中有一個對象的listview
,是通過使用自定義ArrayAdapter
,我想通過單擊listItem
來獲取現在是listItem
的任何對象的字段,但是我不知道要這樣做
我的Content
類是:
public class Content {
public String title;
public String text;
public int id;
public Date date;
}
和我的ContentAdapter
類:
public class ContentAdapter extends ArrayAdapter<Content> {
private ArrayList<Content> objects;
public ContentAdapter(Context context, int textViewResourceId,
ArrayList<Content> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.content_list_item, null);
}
Content i = objects.get(position);
if (i != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView ttd = (TextView) v.findViewById(R.id.toptextdata);
TextView mt = (TextView) v.findViewById(R.id.middletext);
TextView mtd = (TextView) v.findViewById(R.id.middletextdata);
if (tt != null) {
tt.setText("title");
}
if (ttd != null) {
ttd.setText(i.title);
}
if (mt != null) {
mt.setText("text:");
}
if (mtd != null) {
mtd.setText(i.text);
}
}
return v;
}
}
現在,我想通過單擊列表項來獲取日期和ID,但不在列表視圖中顯示它們
我應該在我的自定義arrayAdapter
類中添加id和date字段來執行此操作嗎?
假設您的自定義適配器包含一個Content對象的列表,則必須將OnItemClickListener添加到列表視圖中,如下所示,並獲得單擊的對象並檢索屬性。
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long arg3) {
Content content = (Content ) adapterView
.getItemAtPosition(position);
//from the content object retrieve the attributes you require.
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.