简体   繁体   中英

button change drawable on holding

I'm trying to make this volume button that changes the drawable according to the state that it is put in. So on default the Volume of the device will be on, when pressed it will mute the device, and when its held it'll change the device to vibrating only. Now I am trying to change the drawable of when its put on vibrating, but nothing I try seems to work. I currently have this code in my XML, and I tried playing around with the pressed state but I couldn't get something to work that changes the drawable accordingly.

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

    <item android:drawable="@drawable/ic_volume_down_black_24dp"
    android:state_checked="true" />

    <item android:drawable="@drawable/ic_volume_off_black_24dp"
    android:state_checked="false"/>    
</selector>

Add this android:state_pressed .

<item android:drawable="@drawable/image_you_want_on_press_state"
android:state_pressed="true" />`

Hope this Help.

I created a new drawable xml file, for eg, image_state.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
    <bitmap android:src="@drawable/image_pressed"/>
</item>
<item>
    <bitmap android:src="@drawable/image"/>
</item>
</selector>

And in my layout file, I set the src of the imageView as:

<ImageView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:src="@drawable/image_state"/>

Also check this : Change source image for image view when pressed

Default drawable <item android:drawable="@drawable/ic_volume_off_black_24dp"></item> and for the pressed st <item android:drawable="@drawable/ic_volume_down_black_24dp" android:state_pressed="true" />

<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="200">
    <item android:drawable="@drawable/ic_volume_down_black_24dp" android:state_activated="true" />
    <item android:drawable="@drawable/ic_volume_down_black_24dp" android:state_pressed="true" />
    <item android:drawable="@drawable/ic_volume_off_black_24dp"></item>
</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