简体   繁体   中英

Android Listview selection color with custom background

I've got a problem with android ListView and the selection color. So I've a ListView under a Spinner and for this ListView I've made an ArrayAdapter which is setting a backgroundcolor depending on the item. (This isn't seen at the screenshots)

Now when I click on one item there is no selection color visible. For this i made a selector like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/SelectionColor" android:state_pressed="true" android:state_focused="true"/> </selector>

and added to the listview:

android:listSelector="@drawable/item_selector"
android:drawSelectorOnTop="true"

I added drawSelectorOnTop because without that the selection color isn't visible.

The problem now is that at android 4 it looks like this: click here

and at android 2.3.3 like this: click here

So how can i set the selection color that it looks the same for both versions. And preferably so that the text is still visible.

EDIT: Thanks to Basim. That solves the problem that it looks different depending on the android version. But the text is still not visible if i have the drawSelectorOnTop entry in the listview or the selection isn't visible if i haven't this entry.

Try this selector,

    <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selector style for listrow -->
<item 
 android:state_selected="false"
    android:state_pressed="false" 
    android:drawable="@drawable/normal_shape" />
<item android:state_pressed="true" 
    android:drawable="@drawable/gradient_bg_hover" />
<item android:state_selected="true"
 android:state_pressed="false" 
    android:drawable="@drawable/gradient_bg_hover" />
</selector>

normal_shape.xml

    <?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="270"
        android:endColor="#fefeff"
        android:startColor="#d5dbe7" />

    <stroke
        android:width="1dp"
        android:color="#acd9dd" />

</shape>

gradient_bg_hover.xml

    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <!-- Gradient BgColor for listrow Selected -->
  <gradient
      android:startColor="#d9dd00"
      android:endColor="#e6ea02"
      android:angle="270" />


</shape>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM