Noxmiles
Noxmiles

Reputation: 75

How can I change the Background drawable of my button with onclick in Android?

I have a button with a drawable XML Background

android:background="@drawable/greenbut"

and i want to change the Background to my @drawable/yellowbut by make an onclick on my button.

I tried it with this code, but it seems to be completely wrong. I cannot use the setBackground Function. Can you please help..?

public void colorChanger(View v)
{
    Button changeBut = (Button) findViewById(R.id.button2);
    changeBut.setBackground(R.drawable.yellowbut);
    changeBut.isClickable();
}

Upvotes: 0

Views: 506

Answers (2)

Maniya Joe
Maniya Joe

Reputation: 801

Its as simple as that just follow the code hope it will help

setContentView(R.layout.activity_main);
        final Button changeBut = (Button) findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                button.setBackgroundColor(Color.yellow);
            }
        });

Upvotes: 2

Bidhan
Bidhan

Reputation: 10697

Try this

public void colorChanger(View v)
{
 Button changeBut = (Button) findViewById(R.id.button2);
 changeBut.setBackgroundResource(R.drawable.yellowbut);
 changeBut.isClickable();
}

Upvotes: 2

Related Questions