Friday, December 15, 2017

android - Get current activity root view

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:padding="16dp"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/btn_do_task"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Color Root View"
        />
</LinearLayout>
MainActivity.java

package com.cfsuman.androidcode;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private Button mButton;


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

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

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


        // Set a click listener for button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // You can get the root view of an activity in this way
                //findViewById(android.R.id.content).setBackgroundColor(Color.RED);

                // Some devices this method works fine
                //getWindow().getDecorView().findViewById(android.R.id.content).setBackgroundColor(Color.GREEN);

                // Get the view which you added by activity setContentView() method.
                ViewGroup viewGroup = (ViewGroup) ((ViewGroup) (findViewById(android.R.id.content))).getChildAt(0);
                viewGroup.setBackgroundColor(Color.YELLOW);
            }
        });
    }
}