Android Frame Layout Multiple Views Example

FrameLayout is used to allocate a part of the screen of 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 of how to use FrameLayout.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/5n1uCbOg-wk

  1. Let us see the example app effect first. There are seven color blocks in the screen, all block’s color is unique and different. And the effect is just like neon.
  2. Below is the project files structure, we will create and use the files in this example.
    D:\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\EXAMPLE
    │  .gitignore
    │  build.gradle
    │  gradle.properties
    │  gradlew
    │  gradlew.bat
    │  settings.gradle
    │
    ├─.idea
    │  │  compiler.xml
    │  │  encodings.xml
    │  │  gradle.xml
    │  │  misc.xml
    │  │  modules.xml
    │  │  runConfigurations.xml
    │  │  vcs.xml
    │  │
    │  └─copyright
    │          profiles_settings.xml
    │
    ├─app
    │      │
    │      ├─main
    │      │  │  AndroidManifest.xml
    │      │  │
    │      │  ├─java
    │      │  │  └─com
    │      │  │      └─dev2qa
    │      │  │          └─example
    │      │  │              │  FrameLayoutExampleActivity.java
    │      │  │
    │      │  └─res
    │      │      ├─layout
    │      │      │      activity_frame_layout_example.xml
    │      │      ├─values
    │      │      │      colors.xml

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

  1. This example needs seven colors, so first, we need to define those seven color value variables in colors.xml. You can read the article How To Define Custom Color Variables In Android Studio for detail.
  2. colors.xml, This file is located in the 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.

  1. You can read the article How To Create Activity In Android Studio to learn how to create activity and related layout XML files. This example includes the below files.
  2. activity_frame_layout_example.xml
  3. FrameLayoutExampleActivity.java

2.1 activity_frame_layout_example.xml

  1. This XML file includes one FrameLayout view component. It contains seven TextView view components. Each TextView has an initial unique background color.
  2. Please note each TextView‘s android:layout_gravity attribute value decides the position where this TextView will be placed inside the FrameLayout view component.
  3. The android:layout_gravity attribute value can be the combination of top, center_vertical, bottom, left, center_horizontal and right use the | character
    <?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

  1. There are following points need to be noted in the source code.
  2. If TextView‘s setBackgroundColor(int color) dose not take effect, please use setBackgroundResource(int color) method instead.
  3. Because the android UI and View component are 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

  1. 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>
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x