'How to get access to root view in kotlin?

How can I get the access to root view like in Java, for example:

I know using kotlin extensions we do not need to use findViewById anymore, but I do not know how to handle it. Thank you for any help.

final ViewGroup viewGroup =
                (ViewGroup) ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);
        if (viewGroup instanceof ConstraintLayout) {
         // some logic code
}


Solution 1:[1]

You can also access rootView like this

View rootView = getWindow().getDecorView().getRootView();

So in koltin

val rootView = window.decorView.rootView

Solution 2:[2]

Just place an id on the root and than access it just like you access other Views. Example:

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        **android:id="@+id/mRootView"**
        android:background="#000000"
        tools:context=".MainActivity">

And than in MainActivity (or WhateverActivity/Fragment):

val rootView = mRootView

Solution 3:[3]

In an Activity, you can use:

val rootLayout =  this.window.decorView.rootView

but if you are going to use it in a class, pass the target activity

val rootLayout = activity.window.decorView.rootView 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prithvi Bhola
Solution 2 coroutineDispatcher
Solution 3 Mori