简体   繁体   中英

Android three button states (pressed, not pressed and default)

When the layout loads, all buttons would have default state/bg (without state in selector). When the button is pressed, the background for that button would change to button_pressed="true" and for all the others too button_pressed="false". Is it possible?

With this code a default background is button_pressed="false" item.

<?xml version="1.0" encoding="UTF-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- pressed -->
<item
  android:state_pressed="true"
  android:drawable="@drawable/buttonClicked" />
<item 
android:state_pressed="false"
android:drawable="@drawable/buttonNotClicked" />
<item 
android:drawable="@drawable/button" />
</selector>

Your button_selector should look like below :

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

Here you can have 3 states ie button_normal (when button is in normal condition), button_focused (when button is focused to be pressed) and button_pressed (after the button has been pressed)..

So use 4 different drawables(in /res/drawable folder) with names below :

  1. button_selector.xml (For selector)
  2. button_normal.xml (normal button)
  3. button_focused.xml (button when focused)
  4. button_pressed.xml (button when pressed)

Hope it helps! Let me know if I can help you for anything else...

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