简体   繁体   中英

Any way to change background color of custom shape on click

I have a custom shape for my ListView background. But now it will not change color on click. Is there any way of doing this? Here is my xml for the ListView:

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"

    android:textSize="25sp"
    android:textColor="#ff8d8d8d"/>
<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/textView"
    android:layout_alignParentLeft="true"
    android:textColor="#ff8d8d8d"
    android:textSize="25sp" />
<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/textView1"
    android:layout_alignParentRight="true"
    android:textColor="#ff8d8d8d"
    android:textSize="25sp" />

Here is the CustomShape:

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

<gradient android:startColor="#ffffff"
    android:endColor="#ffd6d4d6"
    android:angle="270"
/>
<corners android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp"
    android:topLeftRadius="10dp" android:topRightRadius="10dp"/>

You can use a selector, but you will be chaining the whole drawable, not only the color . See here

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed_yellow"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused_orange"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_normal_green" />
</selector>

You can understand this list like

switch(state){
  case pressed:
     use some drawable
     break;
   case focused:
     use some other drawable
     break;
   default:
    use the default drawable
}

Create a StateList drawable with a different drawable for the pressed state.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/button_pressed" /> <!-- pressed -->
    <item android:state_focused="true"
          android:drawable="@drawable/button_focused" /> <!-- focused -->
    <item android:state_hovered="true"
          android:drawable="@drawable/button_focused" /> <!-- hovered -->
    <item android:drawable="@drawable/button_normal" /> <!-- default -->
</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