简体   繁体   English

如何在listview onClick()中从POJO获取项目?

[英]How to get Item from POJO in listview onClick()?

I have a POJO, which describes some model (Item?) and some custom Adapter. 我有一个POJO,它描述了一些模型(Item?)和一些自定义适配器。

I am setting my adapter for ListView and then, in onItemClick() I want to get value of one of variables which I had added Into the Item. 我正在为ListView设置我的适配器,然后,在onItemClick()中,我想获得我添加到项目中的一个变量的值。

How I can reach this? 我怎么能达到这个目标?

In my code I am doing something like: 在我的代码中我做的事情如下:

private List<SomeItem> items = new ArrayList();
items.add(new SomeItem(firstValueString, secondValueBitmap, thirdValueString));
SomeAdapter adapter = new SomeAdapter(this, R.layout.list_item, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(
...
@Override
public void onItemClick(){
//How to reach for example firstValueString value of currently clicked item??
}
)

Use android.widget.AdapterView.OnItemClickListener : 使用android.widget.AdapterView.OnItemClickListener

 listView.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view,
          int position, long id) {
        Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "
            + id);
        SomeItem item = items.get(position); // specific item
      }
    });

Based on Android SDK documentation: 基于Android SDK文档:

Implementers can call getItemAtPosition(position) if they need to access the data associated with the selected item. 如果需要访问与所选项目关联的数据,实施者可以调用getItemAtPosition(position)。

If you implement your adapter completely then you can get item like bellow: 如果您完全实现了适配器,那么您可以获得类似下面的项目:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Item item = (Item)parent.getItemAtPosition(position);
    }
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM