Brigitte Fellner
Brigitte Fellner

Reputation: 255

change Image Button System Resource when clicked

I want to change e.g. the btn_star_big_off to btn_star_big_on

Everytime someone clicks on the button the state of that should change. Toogle would be perfect, but I don't know how to combine that. And I don't know how to change state of the button. I found out that I could do that with the drawable XML File but there I only have access to the images I imported, but not the the system resource ones?

The Button:

<ImageButton
                android:id="@+id/imageButton4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@android:drawable/btn_star_big_off" />

And here is the trial from my drawable XML:

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

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

</selector>

Upvotes: 0

Views: 808

Answers (1)

baroni
baroni

Reputation: 176

You need to use ToggleButton

1) In your layout, implement ToggleButton

<TableRow
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1">

    <ToggleButton
    android:layout_width=0dp"
    android:layout_height="wrap_content"
    android:layout_weight=".3"
    android:background="@drawable/my_button"
    android:text=""
    android:textOff=""
    android:textOn=""/>

</TableRow>

2) Creation xml layout in drawable directory ( here my_button.xml )

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:drawable/btn_star_big_on" android:state_pressed="true"/><!-- pressed -->
    <item android:drawable="@android:drawable/btn_star_big_on" android:state_focused="true"/><!-- focused -->
    <item android:drawable="@android:drawable/btn_star_big_on" android:state_checked="true"/>
    <item android:drawable="@android:drawable/btn_star_big_off" android:state_checked="false"/>
    <item android:drawable="@android:drawable/btn_star_big_off"/> <!-- default -->
</selector>

here i add an another state, if you want to have an focused img

Upvotes: 3

Related Questions