9

Change the background of the button's image to clicked and bring it to the origi...

 3 years ago
source link: https://www.codesd.com/item/change-the-background-of-the-button-s-image-to-clicked-and-bring-it-to-the-original-state-when-you-click-again.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Change the background of the button's image to clicked and bring it to the original state when you click again

advertisements

I have a array of buttons in my class as below :

private static final int[] idArray = {R.id.bt0,R.id.bt1,R.id.bt2,R.id.bt3,R.id.bt4,R.id.bt5,R.id.bt6,R.id.bt7,R.id.bt8,R.id.bt9,R.id.bt10,R.id.bt11,R.id.bt12,R.id.bt13,R.id.bt14,R.id.bt15,R.id.bt16,R.id.bt17,R.id.bt18,R.id.bt19,R.id.bt20,R.id.bt21,R.id.bt22,R.id.bt23,R.id.bt24,R.id.bt25,R.id.bt26,R.id.bt27,R.id.bt28,R.id.bt29};
private Button[] bt = new Button[idArray.length];

and have added an image background in my xml as below:

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

<item android:drawable="@drawable/btnew2"    android:state_selected="true"></item>
<item android:drawable="@drawable/btnew1" android:state_pressed="true"></item>
<item android:drawable="@drawable/btnew"></item>
  </selector>

Now, when i press a button the background image is changed (btnew1.gif) and is back to normal when released. I want the color to be changed (it will be a different image, btnew2.gif) when a button is clicked and should return to original color (btnew.gif) when clicked again.

something like state_clicked if something is there like that.

PS: I checked other answers here, but most of them were color changers in java class only and what i am looking for the background image to change(to btnew2.gif) when clicked and be back to original image (btnew.gif) when clicked again.

please suggest suitable solution.


As Niels Masdorp mentioned, you can do it with ToggleButton.

This works because there is a state identifier called state_checkable, similar to state_clickable, which works together with the Checkable interface. ToggleButton implements this interface. You can also create your own widgets implementing this interface, for example extending CompoundButton (abstract).


Example

Use the button in xml:

<ToggleButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/toggle_bg"
    android:textOn="On"
    android:textOff="Off"/>

Define the background in xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/red" android:state_checked="true"/>
    <item android:drawable="@color/blue"/>
</selector>

See also:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK