0

I use selector to create custom buttons with

 <item android:drawable="@drawable/button_bg_selected" android:state_selected="true"></item>
 <item android:drawable="@drawable/button_bg_pressed" android:state_pressed="true"></item>
 <item android:drawable="@drawable/button_bg_normal"></item>

Now I want that the button acts as a state button remaining in the pressed status till is clicked again to return unpressed.

If possible I want to avoid to achieve this setting status programmatically.

Is there a way to do this using selectors (or something similar)?

AndreaF
  • 11,975
  • 27
  • 102
  • 168

1 Answers1

0

Can you use ToggleButton instead of Button?

layout.xml

<ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:textOff="done"
        android:textOn="done"
        android:background="@drawable/test_selector"/>

test_selector.xml

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

    <!-- on checked -->
    <item
        android:state_checked="true"
        android:state_pressed="false"
        android:drawable="@drawable/button_bg_selected" />

    <!-- normal -->
    <item
        android:state_checked="false"
        android:state_pressed="false"
        android:drawable="@drawable/button_bg_normal" />

    <!-- pressed -->
    <item
        android:state_pressed="true"
        android:drawable="@drawable/button_bg_pressed" />

</selector>
ysys
  • 82
  • 4
  • Using ToggleButton with selector as background doesn't allow you to create more elaborate designs. A clickable layout is much more versatile. – AndreaF Mar 31 '19 at 17:47
  • you can do something like this. https://stackoverflow.com/a/17274658/6578666 – Rahul Singh Jun 21 '21 at 08:19