Sergio Paniego
Sergio Paniego

Reputation: 19

Change button background when you click

I wanna place a button which changes between two drawables each time you click. I already have the XML drawable code for that background and the actually button XML. I think it´s smth about my java code.

DRAWABLE XML

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

BUTTON XML

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:layout_below="@+id/imageView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:background="@drawable/fav"
    />

JAVA CODE

    public void OnClickfav() {
    boolean isPressed = false;
    but1.setOnClickListener(buttonListener);  View.OnClickListener buttonListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isPressed) {
                but1.setBackgroundResource(R.drawable.ic_star_border_black_16dp);
            } else {
                but1.setBackgroundResource(R.drawable.ic_star_black_16dp);
            }
            isPressed = !isPressed;
        }
    };
}

Upvotes: 2

Views: 73

Answers (3)

SpiritCrusher
SpiritCrusher

Reputation: 21063

If yo use drawable then why are you doing it by code . Create a selector drawable and set it ass background of button.Like below

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

Upvotes: 0

When you use a selector in xml you should have no need to add code.

Upvotes: 1

sdabet
sdabet

Reputation: 18670

You are using your listener before creating it.

Try this:

boolean isPressed = false;

public void OnClickfav() {
    but1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isPressed) {
                but1.setBackgroundResource(R.drawable.ic_star_border_black_16dp);
            } else {
                but1.setBackgroundResource(R.drawable.ic_star_black_16dp);
            }
            isPressed = !isPressed;
        }
    };
}

Upvotes: 0

Related Questions