简体   繁体   中英

Change color on tapping ListView item with Gradient Drawable

I am able to setup a listview using custom adapter which shows correct output.each list item also has an gradient style see drawable.xml below how do I change the item background to some other gradient on tapping any of them. can I set different gradients for each of the items.?

<shape xmlns:android="http://schemas.android.com/apk/res/android"
 android:shape="rectangle">
<gradient 
android:startColor="#FFFAFAFA" 
android:centerColor="#FFFFFFFF" 
android:endColor="#FFFAFAFA" 
android:angle="90"/>
</shape>

My files...

activity_main.xml....Main xml file

MainActivity.java....Main activity

Item.java.... item selector method

ItemAdaptor.... custom adapter

list_item.xml..... item (textView) styling

I got a color change on tapping with

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
...
android:background="@drawable/listitem_states" >

with res/values/listitem_states.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/listitem_active_color" ></item>
<item
    android:state_pressed="true"
   android:drawable="@color/listitem_active_color" ></item>
<item 
    android:drawable="@color/listitem_bg_color" /> 
</selector> 

I guess you can easily adapt that for gradients.

Try like this..

Add this in drawable

<?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/gradient_bg" />

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

Add in Layout

<ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#FFFFFF"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />

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