0

So I have a ListView, presenting custom Views (each with an image + text). I want those views to have a different appearance when the user selects them. (with an overlay, but for now I try to make it work with just a background)

If I inflate a row with Android.Resource.Layout.TestListItem, it works, the cell shows the selected state when I click.

However, I try to get a similar effect with my custom layout, and I can't get it to work. Is something missing ?

I have this view layout :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/rowbackground">

... (textview and image)

and rowbackground.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="@drawable/bg_a" />
<item android:state_checked="true" android:drawable="@drawable/bg_b" />
<item android:state_pressed="true" android:drawable="@drawable/bg_c" />
<item android:state_selected="false" android:state_checked="false" android:state_pressed="false" android:drawable="@drawable/bg_d"/>
</selector>

But the only two that work are the "default" and the "pressed" states. Not the "selected" one. (I tried also checked, as I see it in some samples)

How can I make my custom-layout View selectable ?

3
  • why android.R.layout.test_list_item works is probably because the test_list_item is a TextView and your layout is a LinearLayout, Commented Jul 21, 2016 at 23:08
  • trye adding android:focusable="false" to your LinearLayout, or just use a TextView as your layout and use its attribut leftDrawable to show an image to the left of the TextView it is more convenient when you have just a TextView and an Image. Commented Jul 21, 2016 at 23:10
  • Thanks. Probably so, but what is it that makes the TextView selectable and not the LinearLayout ? I tried to add android:focusable="false" but it didn't change. Commented Jul 22, 2016 at 7:04

2 Answers 2

1

Ok actually, to handle the "selected" state in a listview, you have to use the activated selector (android:state_activated), like:

<item android:state_activated="true" android:drawable="@drawable/ic_dep" />

Of course that doesn't seem to be documented anywhere. But why, it's so straightforward ? Thanks android

Sign up to request clarification or add additional context in comments.

Comments

0

Add this line in ListView android:background="@drawable/rowbackground" and don't remove this line from Custom layout.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.