简体   繁体   中英

Getting original position of listview after filtering with searchview java

I have a listview populated with this array

arrayList.add("Adam");
arrayList.add("Bob");
arrayList.add("Bob");
arrayList.add("Charlie");

I then have a searchview which properly filters the adapter based on what the user is typing

String text = textField.getText().toString().toLowerCase(Locale.getDefault());
            adapter.getFilter().filter(text);

If the user types "B", "Bob" and "Bob" are the only items displayed in the listview. If I click on the top one, the item position is 0. I need to get the original position of that item(which in this case is 1). I am aware that I could take the context of the row and search the arrayList for the first occurrence of the item. I can then get its position in the unfiltered arraylist. (example)

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

            int i = 0;

            String text = ((TextView) view).getText().toString();

            i = arrayList.indexOf(text);

            if(textLength == 0)
                Toast.makeText(getApplicationContext(), text + " and position is " + position, Toast.LENGTH_SHORT).show();
            else{
                Toast.makeText(getApplicationContext(), text + " and position is " + i, Toast.LENGTH_SHORT).show();
            }

        }
    });

This works regardless of what row I click on, if no filtering has been applied. After filtering, I cannot search the array list for the first occurrence of the row that was selected because there may be more than 1 item with the same text. Also, if I clicked on the second "Bob" (after filtering), it would just return the position of the first "Bob" (which is 1). I understand the problem, I just can't figure out a solution. Is there an efficient way to fix this?

This is just so I can get a proof of concept working. My actual project has multiple array lists. So regardless of their being multiple items in the original array list with the same text (Bob and Bob), the other array lists have different values. That is why I need the original position without searching the array list for the first occurrence of the text. I will not have control of what is in the array list, so I have to account for duplicates.

Please try this

public void onItemClick(AdapterView parent, View view, int position, long id) {

parent.getItemAtPosition(position);

* your code *

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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