-1

I was working on my app, which is nearly finished, and I wanted to implement a feature where the user would click on a button and the background would change color. How would I go about this? I want to have two buttons next to each other that, when clicked change the background color. Button one would change it to color or and button two would change it to color two. I tried coding it in but it doesn't show up the way I want it to so I am asking here because I want to start the buttons from scratch again.

Could anyone help me out with this?

  • Post what you have tried so we can help you figure out what you've done wrong. Otherwise, this post is way too broad for SO – codeMagic Aug 17 '15 at 16:18
  • Check [this thread](http://stackoverflow.com/questions/4761686/how-to-set-background-color-of-activity-to-white-programmatically "How to set background color of Activity to white programmatically?") Put that code into the button click listener – Alberto S. Aug 17 '15 at 16:40

1 Answers1

0

You can change the background color of the activity itself as follows:

This is the XML file for the activity:-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:id="@+id/backgroundId">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RED"
        android:id="@+id/redButton"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="70dp"
        android:onClick="onRedButtonClick"/>
        </RelativeLayout>

This is the java code :

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void onRedButtonClick(View view) {
        RelativeLayout background = (RelativeLayout) findViewBy(R.id.backgroundId);
        background.setBackgroundColor(Color.RED);
    }

Hope this helps.