Ashish Jha
Ashish Jha

Reputation: 183

Changing background color of the layout on a button click in Android

I am a newbie in Android. So please spare me if I am asking a stupid question.

My application contains just one button in a Linear Layout. Requirement is, I have to change the background color of the linear layout of my app on a button click. By default it is WHITE, when I press on the button it should change to some random color and when I press the button again, it should change to the default color (white) again.

button.setBackgroundColor(Color.BLUE) (on the OnClick() method), changes the background color to BLUE, but how to get back to the default color?

Upvotes: 2

Views: 46480

Answers (8)

Jude1995
Jude1995

Reputation: 71

add below code to your layout

android:addStatesFromChildren="true"

Upvotes: 0

Kashmiri Moni Mahanta
Kashmiri Moni Mahanta

Reputation: 26

This code will generate a random color on the background on a button click. By default it is WHITE, when the button is pressed it changes to some random color and when the button is pressed again, it changes to the default color (white) again.

public class MainActivity extends AppCompatActivity {
ImageButton mybutton;
LinearLayout layout;
Boolean color = false;

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

    mybutton = findViewById(R.id.imageButton);
    layout = findViewById(R.id.layout);
    mybutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Random ranNum = new Random();
            if (color==false)
            {
                int myNum = Color.argb(255,ranNum.nextInt(256),ranNum.nextInt(256),ranNum.nextInt(256));
                layout.setBackgroundColor(myNum);
                color = true;
            }
            else
            {
                layout.setBackgroundColor(Color.WHITE);
                color = false;
            }
        }
    });
}}

Upvotes: 0

activity_main.xml

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:id="@+id/ll"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:id="@+id/b1"></Button>
</LinearLayout>

MainActivity.java

package com.example.adouble;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
    Button b1;
    LinearLayout layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1=findViewById(R.id.b1);
        layout=findViewById(R.id.ll);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            layout.setBackgroundColor(Color.RED);
                }
            }
        });
    }
}

Upvotes: 0

Lance Alog
Lance Alog

Reputation: 1

Try to use this code:

android.graphics.drawable.GradientDrawable bg = new android.graphics.drawable.GradientDrawable();

bg.setColor(new android.content.res.ColorStateList(new int[][] {{-android.R.attr.state_pressed}, {android.R.attr.state_pressed}},new int[] {Color.parseColor("#901020"), Color.parseColor("#40109020")}));
bg.setShape(1);
bg.setCornerRadius(10);
bg.setStroke(2, new android.content.res.ColorStateList(new int[][] {{-android.R.attr.state_pressed}, {android.R.attr.state_pressed}}, new int[] {Color.parseColor("#505050"), Color.parseColor("#502010")}));

button1.setBackground(bg);

Upvotes: 0

Param Kapur
Param Kapur

Reputation: 389

This is a completely Java Based approach to your problem. It is as follows;

package com.example.param.background_changer;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.EditText;
import android.graphics.Color;
import android.content.res.Resources;
import android.util.TypedValue;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



//Head
        //Layout type
        final RelativeLayout myLayout = new RelativeLayout(this);

            //Original Background color
            myLayout.setBackgroundColor(Color.BLUE);


//Body

            //Button
            final Button Changer_Button = new Button(this);

                //Button Properties
                Changer_Button.setText("Click Here");
                Changer_Button.setBackgroundColor(Color.GREEN);

                    //Position Properties
                        RelativeLayout.LayoutParams ChangerButton_Position_Details =
                                new RelativeLayout.LayoutParams(
                                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                                        RelativeLayout.LayoutParams.WRAP_CONTENT
                                );
                        ChangerButton_Position_Details.addRule(RelativeLayout.CENTER_HORIZONTAL);
                        ChangerButton_Position_Details.addRule(RelativeLayout.CENTER_VERTICAL);

        myLayout.addView(Changer_Button,ChangerButton_Position_Details);

            //On click listener
            Changer_Button.setOnClickListener(
                    new Button.OnClickListener() {

                        public void onClick(View v) {

                            Changer_Button.setText("Button Clicked");
                            myLayout.setBackgroundColor(Color.RED);
                        }
                    }
            );

        setContentView(myLayout);
    }
}

Upvotes: 0

Dhara Chandarana
Dhara Chandarana

Reputation: 166

i hope this code will help you! take boolean variable when button is clicked.

public class MainActivity extends Activity {
  boolean iscolor = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn = (Button) findViewById(R.id.btn);
    final LinearLayout layout = (LinearLayout) findViewById(R.id.LinearLayout1);

    btn.setOnClickListener(new OnClickListener() {

     @Override
        public void onClick(View view) {

         if(iscolor)
         {
             layout.setBackgroundColor(Color.BLUE);
             iscolor = false;
         }
         else
         {
             layout.setBackgroundColor(Color.WHITE);
             iscolor = true;
         }

        }
    });
}

Upvotes: 1

Kalu Singh Rao
Kalu Singh Rao

Reputation: 1697

Create a shape named button_pressed.xml as follows....

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@color/blue" />

    <stroke
        android:width="4dp"
        android:color="@color/blue" />

    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />

</shape>

Suppose, you have tow button whose ids are R.id.btn and R.id.btn1 as follows...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:background="@drawable/button_pressed"
        android:onClick="onClick"
        android:text="Press Me 1" />        


</LinearLayout>

Write onClick() method as follows...which will allow you to retain the changed color until another button pressed.

Button button;

public void onClick(View v) {

    Drawable dr = getResources().getDrawable(R.drawable.button_pressed);
    dr.setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.SRC_ATOP);

    switch (v.getId()) {
    case R.id.btn:

        if (button == null) {
            button = (Button) findViewById(v.getId());
        } else {
            button.setBackgroundResource(R.drawable.button_pressed);
            button = (Button) findViewById(v.getId());
        }
        button.setBackgroundDrawable(dr);

        break;        


    default:
        break;
    }
}

Reference from here

Upvotes: 0

brahmy adigopula
brahmy adigopula

Reputation: 617

create the xml file in drawble folder

change_colcor.xml

<?xml version="1.0" encoding="utf-8"?> 


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_focused="true"
    android:state_pressed="true"
    android:color="#222222"  />
 <item
    android:state_focused="false"
    android:state_pressed="true"
    android:color="#4aa5d4"  />
</selector>

and then set the XML file to button background

<Button
android:id="@+id/mybutton"
android:background="@drawable/change_colcor" />

Upvotes: 3

Related Questions