简体   繁体   中英

Android ListView: get item's position from its value?

I'm new to Android and Java. I was wondering if there is a way to find the position of a ListView item by its value.

For example:
If I have an item in my ListView that displays the string "Product 1108" How would I get the position of "Product 1108"?

private void updateListView() {
    final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckList);
    Map<String, ?> keys = checkListData.getAll();

    ArrayList<String> checkListStrings = new ArrayList<String>();
    for (Map.Entry<String, ?> entry : keys.entrySet()) {
            if (entry.getKey().equals(currentList + entry.getValue())) {
                checkListStrings.add((String) entry.getValue());
            }
            if (entry.getKey().equals(currentList + entry.getValue() + "Checked")) {
                //set Item to checked / unchecked

            }
        }

        ArrayAdapter<String> checkListArrayAdapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_checked,
                checkListStrings);
                lvCheckList.setAdapter(checkListArrayAdapter);  
                }

This code gets the the the items stored in SharedPreferences and displays them in the ListView. Don't ask me why it works, it just does.

Now see this line:

if (entry.getKey().equals(currentList + entry.getValue() + "Checked")) {
                //set Item to checked / unchecked
    }

What I want to happen here is to set the list item to either checked or unchecked, but I don't think that it's possible because the listview has not been populated yet. So in the ArrayAdapter I need to sort through the items of the listview, find the item with whatever value I'm looking for, and get the position of that item so I can use this code:

lvCheckList.setItemChecked(position, value);

Hopefully this made sense.

If you have a BaseAdapter you should have a something like an ArrayList storing items, which you could use the indexOf(obj) method on.

If you're using an ArrayAdapter you could use getPosition(obj);

Here is an example of looping over an ArrayAdapter (let me know if you use something else):

ArrayAdapter adapter = new YourCustomArrayAdapter();
for(int i = 0; i < adapter.getCount(); i++)
    System.out.println(String.format("String \"%s\" has an index of %d", adapter.getItem(i), i);

This does not use the method getPosition() because our loop feeds us a position that we get the item for.

You can do this

Toast.makeText(getApplicationContext, "The position of the clicked item is " + position, Toast.LENGTH_SHORT).show();

in the listview onItemClickListener() that you will implement

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