skip to Main Content

I am trying to create an Android App in which I want to change my button color when I clicked and that color should be change until I press again.

For Example

On first click color should be red and on click again it should converts to green, it should remain red until I click again.

3

Answers


  1. Chosen as BEST ANSWER

    by default it will be grey but after click on button it will change to orage until press any other button it will remain same (orange) Create two colors resource files in drawable and use them as background like I did. And then use this code in OnClick of button.

                homeButton.setBackgroundResource(R.drawable.bg_gray);
                settingButton.setBackgroundResource(R.drawable.bg_orange);
                isPressed = true;
    

  2. In kotlin you can do like this using flag to keep track of color

    var flag=false 
    
    btn.setOnClickListener{
         flag=!flag
         if(flag)
            it.setBackgroundColor(Color.GREEN)
         else
            it.setBackgroundColor(Color.RED)
        }
    
    Login or Signup to reply.
  3. You can just do a switch by getting the color. Put in your OnClickListener something like

    if(button.getBackgroundColor == COLOR.RED)
        button.setBackgroundColor(COLOR.GREEN);
    else
        button.setBackgroundColor(COLOR.RED);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search