PaulH
PaulH

Reputation: 263

Button Background Image change on click

I have a button that begins life "Unticked" with text going to a Label that says "NO". When you push the button it changes the image to "Ticked" and displays text in a Label as "YES". This all works perfectly. What I can't do or find is how to change it back to "Unticked" and "NO" if I then push it again?

Here is the code for the button:

View.OnClickListener imgButtonHandler9 = new View.OnClickListener() {

        public void onClick(View v) {
            button9.setBackgroundResource(R.drawable.androidnearmisson);


            TextView text = (TextView) findViewById(R.id.textView2);
            text.setText("YES");

        }
    };

Any help will be greatly appreciated.

Many Thanks

Upvotes: 1

Views: 623

Answers (2)

Blaze Tama
Blaze Tama

Reputation: 10948

First move this code to your onCreate :

TextView text = (TextView) findViewById(R.id.textView2);

Inside your onClick :

if(text.getText().toString().equals("NO"))
{
   button9.setBackgroundResource(R.drawable.androidnearmisson);
   text.setText("YES");
}
else
{
   //change what you want
}

Upvotes: 0

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

You can get TextView's current text and make a comparison. If its YES, change to NO, else vice verse:

View.OnClickListener imgButtonHandler9 = new View.OnClickListener() {

    public void onClick(View v) {
        TextView text = (TextView) findViewById(R.id.textView2);
        if(text.getText().toString().equals("NO")){
            button9.setBackgroundResource(R.drawable.androidnearmisson);
            text.setText("YES");
        }
        else {
            button9.setBackgroundResource(R.drawable.otherimage);  //Replace otherimage with proper drawable id
            text.setText("NO");
        }
    }
};

Hope this helps.

Upvotes: 2

Related Questions