Filtering list view and getting correct onclick item

微笑、不失礼 提交于 2019-12-05 06:16:19

I think the problem is in the way you manage your filter. You should get the object with selected id not from the original List (or array) but from the filtered one.

I used something like it in this post from my blog. Hope this help you

 flashsearchList.setOnItemClickListener(new OnItemClickListener() {

        @Override 
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            Integer temp=flashSearchNameMap.get(adapter.getItem(position));

            navigateSearch(temp); 



        }
    }); 

(adapter.getItem(position) will return you the exact list name and in flashSearchNameMap i have stored names and position at beginning from oncreate before applying filtering.So you can get exact position by this

ID and Index are not the same. Of course, you can return item index in getItemId() method of your adapter, but don't expect your items to be identified correctly by this method if you do. Try providing unique ID for each of your items. The idea is somewhat similar to ID of each record in the database, which never changes (and lets you reliably identify each record), and it is easily implemented when you get your data from database.

But if your items don't have unique IDs, and you don't want to bother providing them, there's another approach (see this example code for Adapter below):

public MyAdapter extends BaseAdapter {
    private List<Item> items;
    private List<Item> displayedItems;

    public MyAdapter(List<Item> items) {
        this.items=items;
        this.displayedItems=items;
    }

    public filter(String query) {
        if(query.isEmpty()) {
            displayedItems=items;
        } else {
            displayedItems=new ArrayList<Item>();
            for (Item item : items) {
                displayedItems.add(...) //add items matching your query
            }
        }
        notifyDataSetChanged();
    }

    //...
    //NOTE: we use displayedItems in getSize(), getView() and other callbacks 
}

You can try:

@Override
public boolean hasStableIds() {
    return false;
}

in your adapter

if you are using datbase you have the _id key that you can load in a filtered list as invisible field. Once you click on the item you can query data with _id key. If you aren't using a database you could add a hidden id element in your row element as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!