FrameLayout in Android
Android Framelayout is a ViewGroup subclass that is used to specify the position of multiple views placed on top of each other to represent a single view screen. Generally, we can say FrameLayout simply blocks a particular area on the screen to display a single view. Here, all the child views or elements are added in stack format means the most recently added child will be shown on the top of the screen. But, we can add multiple children’s views and control their positions only by using gravity attributes in FrameLayout.
The FrameLayout can be defined using the code below:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> // Add items or widgets here </FrameLayout>
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Working with the XML Files
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. In this file, we declare the FrameLayout and start adding multiple views like textView, editText, Button, etc. All the views are placed on each other but we displace them according to our requirements. First, we add an image in the background and add other widgets on the top. On the screen, we can see the beautiful login page having an image in the background.
Step 3: Working with the MainActivity File
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. When we have created the layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element from the XML using findViewById.
We need to run using Android Virtual Device(AVD) to see the output.