Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

android - change color of selected listview item

I want to change color of list item when it will press

For that I did like below,

list_item_selector.xml

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

    Selected 
  <item 
    android:state_focused="true" 
    android:state_selected="false" 
    android:drawable="@drawable/list_focused"/> 

  Pressed
  <item 
    android:state_selected="true" 
    android:state_focused="false"
    android:drawable="@drawable/list_selected" />  

</selector> 

I have set the color in colors.xml like below,

 <drawable name="list_focused">#36C170</drawable>
  <drawable name="list_selected">#9EC136</drawable>

and in my ListView I wrote like this,

<ListView
            android:id="@+id/list_centers_complete"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:cacheColorHint="@android:color/transparent"
            android:listSelector="@drawable/list_item_selector" />

but when I am clicking on list item, the whole background color is changed instead of only list item.

How can I solve this? Is there any way?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Apply "@drawable/list_item_selector" to the row of that list(List item) not a List itself..

Something like, your list item (list row)..

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="@drawable/list_item_selector">
        <TextView       android:id="@+id/textForList"
        android:layout_height="fill_parent"
        android:layout_width="wrap_content"
        android:padding="10sp"  />
.
.
.
</LinearLayout>

list_item_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="true">
    <shape>
        <solid android:color="#66FFFFFF" />
    </shape>
</item>
    <item>
    <shape>
        <solid android:color="#FF666666" />
    </shape>
</item>

</selector>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...