How to change color of a button when it is pressed like in a quiz app?

1.9k Views Asked by At

I'm willing to create a android quiz app. I've done all things and my app is completed but I'd like to make the quiz option buttons to change its color when it is pressed by user in order to show whether the answer is correct or wrong. I'd like to show red color button on clicking wrong option and green on correct option .please help me with a simple code that I can embedd in my presaved app java files.

3

There are 3 best solutions below

0
On

You can try this:

someButton.setBackgroundColor(Color.RED); // Wrong option
someButton.setBackgroundColor(Color.GREEN); // Correct option

Refer to View#setBackgroundColor(int) and Color.
A Button is a sub-class of View.

0
On

You can use the combination of android:state_selected and the android:state_enabled properties of the StateListDrawable to achieve the effect through xml.

Your button background can be defined as a drawable below

<selector>
    <item android:drawable="@drawable/default_button_background" />
    <item android:state_selected="true" android:state_enabled="true" android:drawable="@drawable/correct_answer_background" />
    <item android:state_selected="true" android:state_enabled="false" android:drawable="@drawable/wrong_answer_background"
</selector>

and in your code. On Click of the button add this code

boolean isAnswerCorrect = //your logic to check if answer is correct or not
clickedButton.setEnabled(isAnswerCorrect);
0
On

In the following approach, you would need to create two image files for backgrounds on the button to represent correct or false.

Create a folder called Drawable under res and place these two image files in there, then call them as seen below like, R.drawable.filename.

buttonCheckAnswerObject = (Button)findViewById(R.id.buttonCheckAnswer);

buttonCheckAnswerObject.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(final View v) {
          boolean userAnswer;//check if correct
          if (userAnswer){
               v.setBackgroundResource(R.drawable.button_correct_answer_color);
          }
          else {
               v.setBackgroundResource(R.drawable.button_false_answer_color);
          }

     }
});

    enter code here