2013-07-08 122 views
0

我在我的android应用程序中有一个listview对象我已经通过使用我的自定义ArrayAdapter进行了设置,我希望通过单击listItem来获取现在为listItem的任何对象的字段,但我没有任何想法来执行此操作如何在Android中创建对象的列表视图并通过单击列表项访问对象字段?

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和日期字段来执行此操作吗?

回答

0

假设您的自定义适配器包含一个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. 
       } 

      }); 
+0

是的!它的工作原理:)非常感谢你的兄弟:) – mgh