Set layout background color programmatically android

Change complete layout color through MainActivity.java file on button click event.

Layout background color can be easily editable through MainActivity.java programming file. So developer can modify whole layout color on single button click event and the complete layout change at once. So here is the complete step by step tutorial for Set layout background color programmatically android.

android-project-download-code-button

How to Set layout background color programmatically android.

Code for MainActivity.java file.

 package com.android_examples.com.layoutbackgroundprogrammatically;

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


public class MainActivity extends Activity {

 RelativeLayout RL;
 Button BL;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 RL = (RelativeLayout)findViewById(R.id.Layout);
 BL = (Button)findViewById(R.id.button1);
 
 BL.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 // APPLY YOUR COLOR CODE HERE 
 RL.setBackgroundColor(Color.parseColor("#01ff90"));
 
 }
 }); 
 }
}

Code for activity_main.xml layout file.

<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"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.layoutbackgroundprogrammatically.MainActivity"
 android:id="@+id/Layout" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="CLICK HERE TO CHANGE COMPLETE LAYOUT COLOR Programmatically"
 />

</RelativeLayout>

Screenshot before apply color :

before layout change

After color change :

Set layout background color programmatically android

Click here to download Set layout background color programmatically android project.

Leave a Reply

Your email address will not be published. Required fields are marked *