Android Frame Layout Multiple Views Example

FrameLayout is used to allocate a part of screen to a single View component to display. It is similar to CardLayout in Swing programming. A FrameLayout component can include multiple view components. The position of each child view component is decided by it’s android:layout_gravity attribute value. This article will show you an example about how to use FrameLayout.

Let us see the example app effect first. There are seven color block in the screen, all block’s color is unique and different. And the effect is just like a neon.

android frame layout multiple view example

Below is the project files structure, we will create and use the files in red rectangle.

android framelayout example project files structure

1. Create Seven Int Color Value Variable In Colors.xml.

This example need seven color, so first we need to define those seven color value variables in colors.xml. You can read article How To Define Custom Color Variables In Android Studio for detail.

colors.xml

This file is located in app / res / values folder.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorRed">#ff0000</color>
    <color name="colorOrange">#f1a86c</color>
    <color name="colorYellow">#fff200</color>
    <color name="colorGreen">#00dd12</color>
    <color name="colorCyan">#00b4dd</color>
    <color name="colorBlue">#000bdd</color>
    <color name="colorPurple">#9700dd</color>
</resources>

2. Create FrameLayout Example Activity And It’s Layout Xml File.

You can read article How To Create Activity In Android Studio to learn how to create activity and related layout xml file. This example include below files.

  1. activity_frame_layout_example.xml
  2. FrameLayoutExampleActivity.java

2.1 activity_frame_layout_example.xml

This xml file include one FrameLayout view component. It contains seven TextView view components. Each TextView has a initial unique background color.

Please Note : Each TextView’s  android:layout_gravity attribute value decides the position that this TextView will place inside the FrameLayout view component.

READ :   Mobile Responsive Registration Form In Html Example

The android:layout_gravity attribute value can be the combination of top, center_vertical, bottom, left, center_horizontal and right use | charactor

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.dev2qa.example.FrameLayoutExampleActivity">


    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is TextView1."
            android:background="@color/colorRed"
            android:layout_gravity="top|left" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is TextView2."
            android:background="@color/colorOrange"
            android:layout_gravity="top|center_horizontal" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is TextView3."
            android:background="@color/colorYellow"
            android:layout_gravity="top|right" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is TextView4."
            android:background="@color/colorGreen"
            android:layout_gravity="center_vertical|left" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is TextView5."
            android:background="@color/colorCyan"
            android:layout_gravity="center_vertical|center_horizontal" />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is TextView6."
            android:background="@color/colorBlue"
            android:layout_gravity="center_vertical|right"/>

        <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is TextView7."
            android:background="@color/colorPurple"
            android:layout_gravity="bottom|left" />
    </FrameLayout>
</android.support.constraint.ConstraintLayout>

2.2 FrameLayoutExampleActivity.java

There are following points need to be noted in source code.

  1. If TextView’s setBackgroundColor(int color) dose not take effect, please use setBackgroundResource(int color) method instead.
  2. Because android UI and View component is not thread safe, so we use Timer object instead of Thread object to update the block color.
package com.dev2qa.example;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

public class FrameLayoutExampleActivity extends AppCompatActivity {

    // Create a TextView array to store TextView components in FrameLayout layout component.
    private TextView textViewArr[] = new TextView[7];

    // Store current color value.
    private int currColor = 0;

    // Initialise an int color array.
    private final int[] colorArr = new int[]{
            R.color.colorRed,
            R.color.colorOrange,
            R.color.colorYellow,
            R.color.colorGreen,
            R.color.colorCyan,
            R.color.colorBlue,
            R.color.colorPurple
    };

    // Initialise an int view id array.
    private final int[] viewIdArray = new int[]{
            R.id.textView1,
            R.id.textView2,
            R.id.textView3,
            R.id.textView4,
            R.id.textView5,
            R.id.textView6,
            R.id.textView7
    };

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

        for(int i=0;i<7;i++)
        {
            textViewArr[i] = (TextView)this.findViewById(viewIdArray[i]);
            // Set each TextView component height to 500 pixel.
            textViewArr[i].setHeight(500);
            //textViewArr[i].setText("haha");
            //textViewArr[i].setTextColor(Color.GREEN);
            //textViewArr[i].setBackgroundResource(colorArr[6-i]);
        }

        final Handler textViewHandler = new Handler()
        {
            // When this handler receive a message.
            @Override
            public void handleMessage(Message msg) {
                // what is a user defined int value that can be used to identify message source object.
                // msg.what == 123 means the message was sent from this application.
                if(msg.what == 123)
                {
                    // Loop in the TextView Array.
                    for(int i=0;i < viewIdArray.length;i++)
                    {
                        // Get current TextView object.
                        TextView currTextView = textViewArr[i];

                        // Calculate current TextView background color.index.
                        int colorArrIdx = i + currColor;
                        if(colorArrIdx >= colorArr.length)
                        {
                            // Use color value from color array beginning.
                            colorArrIdx = colorArrIdx - colorArr.length;
                        }

                        // Set current TextView object background color.
                        currTextView.setBackgroundResource(colorArr[colorArrIdx]);
                    }
                }

                super.handleMessage(msg);
            }
        };

        // Create a TimerTask object.
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                // Current color plus one.
                currColor++;
                if(currColor == colorArr.length - 1)
                {
                    currColor = 0;
                }

                // Create and send a message.
                Message msg = new Message();
                // Define an int message source identifier value.
                msg.what = 123;
                textViewHandler.sendMessage(msg);
            }
        };

        // Schedule the TimerTask object execute every 1 second.
        Timer timer = new Timer();
        timer.schedule(timerTask, 0, 200);
    }
}

3. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dev2qa.example">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".FrameLayoutExampleActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
(Visited 3,096 times, 3 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.