Ahmet Urun Ahmet Urun - 3 months ago 10
Android Question

Changing color of the row that has been selected by longclick in ListView Android

I want to highlight the selected row on my

ListView
when it's long pressed. Now I'm able to do that when the row just clicked as in photo:

selected row.jpg

How can I do this with long click?
My
setOnItemLongClickListener
function so far:

user_data.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
selected_note = adapterView.getItemAtPosition(i).toString();
user_data.setItemChecked(i,true);
return true;
}
});

Answer

Edit: Then this might help

In your list view layout

android:background="@drawable/key"

Create key.xml

<?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>

Add this to your listview onClickListener:

listView.setOnItemClickListener(new OnItemClickListener() {

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

You can also define 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>
Comments