In this Android kotlin example we will learn how to get the root view of the current activity. We know that ViewGroup is the base class for other view and view containers, so by using the ViewGroup we will find the current root view of the activity.
This ViewGroup will have the fixed Id for the every activity. android.R.id.content will give the entire view of the present activity.
Then from this instance we will find the root view of the current activity by get the first child of the ViewGroup object.
val viewGroup =
(findViewById<View>(android.R.id.content) as ViewGroup).getChildAt(0) as ViewGroup
|
Let's create Android example to find the root view of the current activity.
In this we also cover how to work with button in android and button click event.
package com.rrtutors.kotlinexample2021
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.view.ViewGroup
class RootViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_root_view)
var btn_event=findViewById<Button>(R.id.btn_event);
btn_event.setOnClickListener {
val viewGroup =
(findViewById<View>(android.R.id.content) as ViewGroup).getChildAt(0) as ViewGroup
viewGroup.setBackgroundColor(Color.RED)
}
}
}
|
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_event" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Check Root View" /> </LinearLayout> |
In this example we will find the root view by button onclick event and apply the color to the root view
Conclusion: In this android example we covered how to get the root view of the current activity and also find how to work with button and button click events with android kotlin.
Article Contributed By :
|
|
|
|
3132 Views |