How to refer to the original position of a list item when text filter is enabled?

后端 未结 4 922
甜味超标
甜味超标 2021-01-15 13:58

When I use edit text to filter the items, the list positions get all messed up and the items no longer call the proper intent. Any help is appreciated

lv.se         


        
4条回答
  •  甜味超标
    2021-01-15 14:29

    Assuming you are using a custom bean object to store your name & website values and an ArrayAdapter to show them in your ListView, like so

    public class NamedLink {
        final String mName;
        final String mWebsite; 
        public NamedLink(String name, String website) {
            mName = name;
            mWebsite = website;
        }
        @Override
        public String toString() {
            return mName;
        }
    }
    

    With an adapter, defined something like this:

    mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, mLinks) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(WhateverYourActivityIsNamed.this).inflate(android.R.layout.simple_list_item_2, null);
                }
                NamedLink link = getItem(position);
                // This probably deserves a ViewHolder
                ((TextView) convertView.findViewById(android.R.id.text1)).setText(link.getName());
                ((TextView) convertView.findViewById(android.R.id.text2)).setText(link.getWebsite());
                return convertView;
            }
        };
    

    When you filter the array adapter it will match against the beans #toString(), which in this case returns the name. When filtered, the array adapter maintains a properly indexed copy of your list of beans internally - i.e. you can use the position you get in the click listener like this:

    getListView().setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                // getItemAtPosition() will return a NamedLink from the filtered
                // list maintained inside the ArrayAdapter
                NamedLink link = (NamedLink) parent.getItemAtPosition(position);
                Intent openDetails = new Intent(Test.this, ResourceDetails.class);
                Bundle b = new Bundle();            
                b.putString("name", link.getName());
                b.putString("web", link.getWebsite());
                openDetails.putExtras(b);
                startActivity(openDetails);  
            }
        });
    

提交回复
热议问题