Friday, December 15, 2017

android - Get current activity root view

MainActivity.java

package com.cfsuman.androidtutorials;

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


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

        // Get the widgets reference from XML layout
        Button button = findViewById(R.id.button);


        // Set a click listener for Button widget
        button.setOnClickListener(view -> {
            // Get the view which you added by
            // activity setContentView() method.
            ViewGroup viewGroup = (ViewGroup) ((ViewGroup)
                    (findViewById(android.R.id.content)))
                    .getChildAt(0);

            viewGroup.setBackgroundColor(
                    Color.parseColor("#676767")
            );
        });
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Color Activity Root View"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>