How to Change Android Button Background Color on Button Click

You can achieve a toggle effect with android background color when the button is clicked. There are two scenarios here.

  1. To change android button background color when the button is click
  2. To toggle between two colors when the button is click.

We will focus on the second option . But the good thing is that you can easily adopt this code to work in the case of option 1.

activity_change_button_color.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".button.ChangeButtonColorActivity">

    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/change_background_color"
        android:background="@color/colorPrimary"
        android:padding="16dp"
        android:textColor="#ffffff"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

ChangeButtonColorActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.inducesmile.inducesmile_button.R;

public class ChangeButtonColorActivity extends AppCompatActivity {

    private int buttonState = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_button_color);

        final Button button = findViewById(R.id.button6);

        //Add OnClickEvents to the button that responds to the user event
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(buttonState % 2 == 0){
                   button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                    Toast.makeText(getBaseContext(), "Button background color green", Toast.LENGTH_SHORT).show();
                }
                else{
                    button.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                    Toast.makeText(getBaseContext(), "Button background color accent", Toast.LENGTH_SHORT).show();
                }
                buttonState++;
            }
        });
    }
}

android button background

 

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.