Selection and deselection of items in a Listview - Android

Asked

Viewed 640 times

1

I’ve got a listview that extends a basedapter. And following this one’s lead topical with the @ramaral reply I was able to make the item select and select but now how do I check if the item is selected?

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



            if (view.isSelected()){
                Toast.makeText(lista.getContext(),"SELECIONADO",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(lista.getContext(),"NÃO SELECIONADO",Toast.LENGTH_SHORT).show();
            }



        }
    });

With this code it is only displaying : "NOT SELECTED" Regardless of whether the item is selected or not. Can you help me?

1 answer

1


To keep the color of the listview item by pressing it, include the following line in your listview layout:

android:background="@drawable/bg_key"

Then set bg_key.xml in the drawable folder to look like this:

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_selected="true"
        android:drawable="@color/pressed_color"/>
    <item
        android:drawable="@color/default_color" />
</selector>

Finally, include this in your listview Onclicklistener:

listView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
        view.setSelected(true);
        ... //Anything
    }
});

In this way, only one item will be color-selected at any time. You can set your color values in res/values/Colors.xml with something like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="pressed_color">#4d90fe</color>
    <color name="default_color">#ffffff</color>
</resources>
  • It worked, vlw!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.