2013-07-08 45 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