Hello Friends, Today We will teach you how to change the layout background color on Button click using View in Android
Follow the Steps
Step 1. Create a new project.
Step 2. Create a Button and Provide the id.
activity_main.xml :-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_centerInParent="true"
android:id="@+id/btn"/>
</RelativeLayout>
Step 3. Now Create Object of View and Button in Java File
MainActivity.java :-
We use View v = this.getWindow().getDecorView(); for get current window view for change the background color of current window ( Current Layout ).
Now Run the app and see the output:-
When the app is run:-
MainActivity.java :-
package com.akshayarora.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button;
View v;
boolean isColor = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
v = this.getWindow().getDecorView();
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@SuppressLint("ResourceType")
@Override
public void onClick(View view) {
if (isColor) {
v.setBackgroundResource(android.R.color.holo_blue_dark);
isColor = false;
} else {
v.setBackgroundResource(android.R.color.white);
isColor = true;
}
}
});
}
}
Now Run the app and see the output:-
When the app is run:-
Now Click on Button:-
Click again on Button:-
Enjoy!




No comments:
Post a Comment
Note: Only a member of this blog may post a comment.