Selecting and deselecting items in a ListView - Android

1

I have a listview that extends a baseadapter. And following the hint of this topic with the @ramaral's answer I was able to make the item select and deselect but now how do I check to see 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 whether the item is selected or not. Can you help me?

    
asked by anonymous 27.07.2016 / 08:32

1 answer

1

To keep the color of the listview item when you press it, include the following line in your listview layout:

android:background="@drawable/bg_key"

Next, set bg_key.xml in the drawable folder 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 OnClickListener listview:

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 to 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>
    
27.07.2016 / 15:30