how to change the image of a button with every click?
Asked Answered
T

3

7

I created a button in the layout . In the Drawable folder I created a XML file named btn01_state. The btn01_state.xml is assigned to the button i created through "android:background=@drawable/btn01_state"

Now, the button has a default image img1.when i click on the button, the image1 changes to img2, and once i release the clicked mouse button, the image2 again changed to img1 again.

what i want to do is,to change the image of the button with evey click.

for an example, initially btn01 has img01

if btn01 is pressed==> set img of btn01 to img02 and keep img02 till the btn01 is pressed again. Now, btn01 has img02 on it.

When btn01 is pressed, set img01 to btn01.

I hope this clarified more what i want to do.

btn_selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/android_blue"
      android:state_pressed="true" />
<item android:drawable="@drawable/ic_launcher"
      android:state_focused="true" />
<item android:drawable="@drawable/ic_launcher" />

main.xml

<Button 
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:id="@+id/btn01"
    android:background="@drawable/btn01_state"/>
Towage answered 6/5, 2012 at 11:53 Comment(0)
S
18

You can do it easily within the code.

boolean isPressed = false;
button.setOnClickListener(buttonListener);

OnClickListener buttonListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        if(isPressed)
           button.setBackgroundResource(R.drawable.icon1);
        else
           button.setBackgroundResource(R.drawable.icon2);

        isPressed = !isPressed;
   }
};
Stralsund answered 6/5, 2012 at 12:42 Comment(2)
Doesn't work with me. It only calles onClick when the button is pressed and not when the button is released. So It will only do one of the branch on each click.Espresso
@ZdravkoDonev - it is because the op asked for how to change button image with clicks, not touchs. If you want to change button state you should probably check this link - https://mcmap.net/q/167724/-android-button-selectorStralsund
M
1

Simple way

btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
    btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.locationbutton_on));
                }
        }); 
Malleable answered 6/5, 2012 at 12:40 Comment(0)
R
0

Make it in code perhaps. Put a listener on the button and when the button is clicked the background is changed.

Rurik answered 6/5, 2012 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.