How to change the color of a Listview item while it is being pressed?

Asked

Viewed 724 times

1

By default, when you click on an item, it changes color at the time of the click, but I changed my listview and this click is not working. Does anyone know how to implement it if it is some ready view method, an animation or some check with a setBackground? I tested do a check but it did not work as it should. I thank you already.

I need something like this image, but when the user drops the item back to normal color.

inserir a descrição da imagem aqui

2 answers

2

Create a selector for your list, with the desired colors for clicks, longClicks, etc:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
    <item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
    <item android:drawable="@color/black" /> <!-- default -->
</selector> 

Then call your selector inside your Listview:

<ListView android:id="@+id/list" 
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:listSelector="@drawable/meuSeletor" />

1

Daniel, all right ?

The following is a link from the official Google documentation regarding this feature. It explains well what each attribute does and gives an example at the end. Follow some excerpts from the page:

Create the res/color/button_text.xml file with the contents below.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
      android:color="#ffff0000"/> <!-- pressed -->
<item android:state_focused="true"
      android:color="#ff0000ff"/> <!-- focused -->
<item android:color="#ff000000"/> <!-- default -->
</selector>

And here an example of implementation, note that in the attribute android:textColor we refer to the res/color/button_text.xml that we did above:

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:textColor="@color/button_text" />

Link to the documentation page here.

Browser other questions tagged

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