Android FrameLayout Tutorial With Example In Android Studio

android framelayout, android adapter, android baseadapter, android simpleadapter, android custom simple adapter, android arrayadapter, android custom arrayadapter, android listview tutorial

Android FrameLayout Tutorial With Example is today’s chapter.

FrameLayout is the easiest layout to hold the child view. It is generally used to block the certain area of the screen.

Usually, framelayout have single child view to reduce the complexity of making the screen responsive across all the screen sizes.

If framelayout contains multiple child views then they might overlap each other in different screen sizes and responsiveness of the layout becomes just a dream!

For example, when you want to have a fragment along with button, you should put the fragment in the framelayout,

while you should keep the button in the activity’s layout XML file.

You can, however, add multiple children to a FrameLayout,

For that you need to control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.

FrameLayout add it’s child in the stack format.

Meaning is that it will add the most recently added child on the top.

XML Attributes Of FramLayout

Following are the important and useful attributes of the FrameLayout.

1. android:id

This attribute will give the unique identity to the framelayout.

When you want to access the framelayout from the JAVA class, this id will give you the reference via findViewById() method.

Value of this attribute should be unique across the whole android app to reduce the complexity.

Below is the code example to use id

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frame"
    android:layout_width="200dp"
    android:layout_height="300dp"
    android:foreground="@color/colorAccent"
    tools:context=".MainActivity">

2. android:foreground

This attribute allows us to draw to certain view on the whole framelayout.

The value of this property can be a color, a drawable file or a simple image.

Possible color values are “#rgb”, “#argb”, “#rrggbb”, or “#aarrggbb” according to various RGB values.

Now make a new project in android studio.

Do not touch the MainActivity.java class. Keep it as it is.

Add the below source code in activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frame"
    android:layout_width="200dp"
    android:layout_height="300dp"
    android:foreground="@color/colorAccent"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:text="Button"/>

    <TextView
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:textSize="20sp"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:text="I am TextView" />

</FrameLayout>

Above file will generate the following output

android framelayout

 

 

Framelayout is the main layout in the above file.

Now foreground attribute have a value of transparent pink color with 173 opacity.

Because pink color is transparent, we can see the TextView and Button through it, Otherwise solid color will cover them both completely.

So you can imagine that foreground value will cover the whole framelayout.

3. android:visibility

We can apply this attribute to any child of the framelayout.

Possible values for visibility are visible, invisible and gone.

  • Visible means that the view is present and we can also see it.
  • Invisible means that the view is present and we can not see it.
  • Gone means that view is not present and so we can not see it.

Code example can be like below

 android:visibility="visible"

Remove all the code from your activity_main.xml file and add the below code

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frame"
    android:layout_width="200dp"
    android:layout_height="300dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:visibility="invisible"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:text="I am TextView" />

</FrameLayout>

Output will be like the following image


You can see that Textview is present (blue border rectangle) but we can not see it.

Similarly, you can change the value as Visible and Gone and see the output.

4. android:measureAllChildren

This property defines whether to measure the all the children including those who are with “Gone” visibility state or to measure only those who have “visible” or “invisible” state.

This property can have “True” or “False” value.

If true then it will include the child with gone visibility otherwise not.

Let us understand this example,

In your activity_main.xml file, add the below code

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/framelayout"
    android:layout_width="200dp"
    android:layout_height="300dp"
    android:measureAllChildren="true"
    tools:context=".MainActivity">

     <TextView
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:visibility="gone"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:text="I am TextView" />

</FrameLayout>

In the MainActivity.java file, add the below code

import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        FrameLayout frame=(FrameLayout)findViewById(R.id.framelayout);
        frame.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int width = frame.getMeasuredWidth();
        int height = frame.getMeasuredHeight();


        int dpwidth = (int) (width / Resources.getSystem().getDisplayMetrics().density) - 20;
        int dpheight = (int) (height / Resources.getSystem().getDisplayMetrics().density) - 20;

        Toast.makeText(getApplicationContext(),"width="+dpwidth+"  height="+dpheight, Toast.LENGTH_SHORT).show();

    }
}

When you run the above code, we will have the toast with values “width=100 and height=50” (Which are the width and height of the TextView.)

Width and Height are in the dp format.

Visibility of Textview is gone but because measureAllchildren is true, compiler will take the textview into consideration.

Methods of FrameLayout

To control the framelayout from JAVA class, android gives us the following in-built methods to use.

1. generateLayoutParams(AttributeSet attrs)

It Returns a new set of layout parameters based on the supplied attributes set.

2. getAccessibilityClassName()

Return the class name of this object to be used for accessibility purposes.

3. getMeasureAllChildren()

Determines whether all children, or just those in the VISIBLE or INVISIBLE state, are considered when measuring.

It will return boolean value. (True or False)

If it returns false then compiler will consider only VISIBLE or INVISIBLE state of children of framelayout.

For true, it will consider VISIBLE, INVISIBLE and GONE state of children of framelayout.

4. setForegroundGravity(int foregroundGravity)

Describes how the foreground is positioned.

5. setMeasureAllChildren(boolean measureAll)

Sets whether to consider all children, or just those in the VISIBLE or INVISIBLE state, when measuring.

6. shouldDelayChildPressedState()

Return true if the pressed state should be delayed for children or descendants of this ViewGroup.

7. generateDefaultLayoutParams()

Returns a set of layout parameters with a width of ViewGroup.LayoutParams.MATCH_PARENT, and a height of ViewGroup.LayoutParams.MATCH_PARENT.

8. generateLayoutParams(ViewGroup.LayoutParams lp)

Returns a safe set of layout parameters based on the supplied layout params.

9. onLayout(boolean changed, int left, int top, int right, int bottom)

Called from layout when this view should assign a size and position to each of its children.

10. onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overridden by sub classes to provide accurate and efficient measurement of their contents.

NOTE: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass’ onMeasure(int, int) is a valid use.

Examples of FrameLayout

Make a new project in android studio if do not have already.

Code for MainActivity.java should look like the below

public class MainActivity extends AppCompatActivity {

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

In your activity_main.xml file, write down the following lines

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/framelayout"
    android:layout_width="200dp"
    android:layout_height="300dp"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp"
        android:layout_marginLeft="20dp"
        android:text="Button"/>

    <TextView
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:text="I am TextView" />

</FrameLayout>

Above code will produce the below output

android framelayout

Big rectangle with blue borders is the area covered by the FrameLayout.

In this framelayout, I have added a textview and a button.

Naturally, children of framelayout covers each other but in the above code I have used proper layout_margin properties to avoid this overlapping.

Now if you set the layout_margitTop of button as “0” you will have the following preview.

Code

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp" // 0 dp for button
        android:layout_marginLeft="20dp"
        android:text="Button"/>

Preview


In the above image, you can clearly see that Button is overlapping the TextView.

That is why, it is recommended to use only single view inside the framelayout.

Example 2

Again, do not change anything in the MainActivity.java file.

Code for activity_main.xml is like the below

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/framelayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@mipmap/ic_launcher_round"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="0dp"
        android:text="Button"/>

    <TextView
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:textSize="20sp"
        android:layout_gravity="center"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:text="I am TextView" />

</FrameLayout>

Following is the view of the above source code

android framelayout

 

I have given full width and height to the framelayout. So it will cover the whole screen.

Both children, textview and button are overlapping the android logo image.

Now first child of framelayout is the Imageview with full height and width.

So you can see in above image that Image of android logo has the full screen size.

Second child is button, with layout_gravity as a “center_horizontal“.

Thus, button is at the center horizontally.

TextView has the layout_gravity as a “center“, so it is at the center of the whole screen (horizontally and vertically)

Thus, it was all the necessary information about FrameLayout.