You are on page 1of 33

Android RadioButton

RadioButton is a two states button which is either checked or unchecked. If a single radio button is
unchecked, we can click it to make checked radio button. Once a radio button is checked, it cannot be
marked as unchecked by user.
RadioButton is generally used with RadioGroup. RadioGroup contains several radio buttons, marking one
radio button as checked makes all other radio buttons as unchecked.
and RadioGroup Views

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
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=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select your Subject ?"
android:textStyle="bold"
android:layout_marginLeft="10dp"
android:textSize="20sp"/>

<!-- add RadioGroup which contain the many RadioButton-->


<RadioGroup
android:layout_marginTop="50dp"
android:id="@+id/groupradio"
android:layout_marginLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- In RadioGroup create the 1 Radio Button-->


<!-- like this we will add some more Radio Button-->
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/radia_id1"
android:text="DBMS"
android:textSize="20sp"/>

<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/radia_id2"
android:text="C/C++ Programming"
android:textSize="20sp"/>

<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/radia_id3"
android:text="Data Structure"
android:textSize="20sp"/>

<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/radia_id4"
android:text="Algorithms"
android:textSize="20sp"/>
</RadioGroup>

<!-- add button For Submit the Selected item-->


<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="@+id/submit"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginTop="200dp"
android:layout_marginLeft="180dp"
/>

<!-- add clear button for clear the selected item-->


<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"
android:id="@+id/clear"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="200dp"
android:layout_marginLeft="20dp"
/>

</RelativeLayout>

___________________________

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.RadioButton;

import android.widget.RadioGroup;

import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

// Define the object for Radio Group,

// Submit and Clear buttons

private RadioGroup radioGroup;

Button submit, clear;

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Bind the components to their respective objects

// by assigning their IDs

// with the help of findViewById() method

submit = (Button)findViewById(R.id.submit);

clear = (Button)findViewById(R.id.clear);

radioGroup = (RadioGroup)findViewById(R.id.groupradio);

// Uncheck or reset the radio buttons initially

radioGroup.clearCheck();
// Add the Listener to the RadioGroup

radioGroup.setOnCheckedChangeListener(

new RadioGroup

.OnCheckedChangeListener() {

@Override

// The flow will come here when

// any of the radio buttons in the radioGroup

// has been clicked

// Check which radio button has been clicked

public void onCheckedChanged(RadioGroup group,

int
checkedId)

// Get the selected Radio Button

RadioButton

radioButton

= (RadioButton)group

.findViewById(checkedId);

});
// Add the Listener to the Submit Button

submit.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v)

// When submit button is clicked,

// Ge the Radio Button which is set

// If no Radio Button is set, -1 will be returned

int selectedId = radioGroup.getCheckedRadioButtonId();

if (selectedId == -1) {

Toast.makeText(MainActivity.this,

"No answer has been selected",

Toast.LENGTH_SHORT)

.show();

else {

RadioButton radioButton

= (RadioButton)radioGroup

.findViewById(selectedId);
// Now display the value of selected item

// by the Toast message

Toast.makeText(MainActivity.this,

radioButton.getText(),

Toast.LENGTH_SHORT)

.show();

});

// Add the Listener to the Submit Button

clear.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v)

// Clear RadioGroup

// i.e. reset all the Radio Buttons

radioGroup.clearCheck();

});

}
}

Android CheckBox is a type of two state button either checked or unchecked.


There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the user,
activate/deactivate the specific action etc.
Android CheckBox class is the subclass of CompoundButton class.

Android CheckBox class


The android.widget.CheckBox class provides the facility of creating the CheckBoxes.

Methods of CheckBox class


There are many inherited methods of View, TextView, and Button classes in the CheckBox class. Some of
them are as follows:

Method Description

public boolean isChecked() Returns true if it is checked otherwise false.

public void setChecked(boolean status) Changes the state of the CheckBox.

Android CheckBox Example

activity_main.xml

File: activity_main.xml

1. <?xml version="1.0" encoding="utf-8"?>


2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/an
droid"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="examplet.com.checkbox.MainActivity">
8.
9.
10. <CheckBox
11. android:id="@+id/checkBox"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_marginLeft="144dp"
15. android:layout_marginTop="68dp"
16. android:text="Pizza"
17. app:layout_constraintStart_toStartOf="parent"
18. app:layout_constraintTop_toTopOf="parent" />
19.
20. <CheckBox
21. android:id="@+id/checkBox2"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_marginLeft="144dp"
25. android:layout_marginTop="28dp"
26. android:text="Coffee"
27. app:layout_constraintStart_toStartOf="parent"
28. app:layout_constraintTop_toBottomOf="@+id/checkBox" />
29.
30. <CheckBox
31. android:id="@+id/checkBox3"
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_marginLeft="144dp"
35. android:layout_marginTop="28dp"
36. android:text="Burger"
37. app:layout_constraintStart_toStartOf="parent"
38. app:layout_constraintTop_toBottomOf="@+id/checkBox2" />
39.
40. <Button
41. android:id="@+id/button"
42. android:layout_width="wrap_content"
43. android:layout_height="wrap_content"
44. android:layout_marginLeft="144dp"
45. android:layout_marginTop="184dp"
46. android:text="Order"
47. app:layout_constraintStart_toStartOf="parent"
48. app:layout_constraintTop_toBottomOf="@+id/checkBox3" />
49.
50. </android.support.constraint.ConstraintLayout>

Activity class
Let's write the code to check which toggle button is ON/OFF.
File: MainActivity.java
1. package example.com.checkbox;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.CheckBox;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. CheckBox pizza,coffe,burger;
12. Button buttonOrder;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. addListenerOnButtonClick();
18. }
19. public void addListenerOnButtonClick(){
20. //Getting instance of CheckBoxes and Button from the activty_main.xml file
21. pizza=(CheckBox)findViewById(R.id.checkBox);
22. coffe=(CheckBox)findViewById(R.id.checkBox2);
23. burger=(CheckBox)findViewById(R.id.checkBox3);
24. buttonOrder=(Button)findViewById(R.id.button);
25.
26. //Applying the Listener on the Button click
27. buttonOrder.setOnClickListener(new View.OnClickListener(){
28.
29. @Override
30. public void onClick(View view) {
31. int totalamount=0;
32. StringBuilder result=new StringBuilder();
33. result.append("Selected Items:");
34. if(pizza.isChecked()){
35. result.append("\nPizza 100Rs");
36. totalamount+=100;
37. }
38. if(coffe.isChecked()){
39. result.append("\nCoffe 50Rs");
40. totalamount+=50;
41. }
42. if(burger.isChecked()){
43. result.append("\nBurger 120Rs");
44. totalamount+=120;
45. }
46. result.append("\nTotal: "+totalamount+"Rs");
47. //Displaying the message on the toast
48. Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
49. }
50.
51. });
52. }
53. }

Output:

What is Android View Group?

A View Group is a subclass of the ViewClass and can be considered as a superclass of Layouts. It provides
an invisible container to hold the views or layouts. ViewGroup instances and views work together as a
container for Layouts. To understand in simpler words it can be understood as a special view that can
hold other views that are often known as a child view.

Following are certain commonly used subclasses for ViewGroup:


● LinearLayout
● RelativeLayout
● FrameLayout
● GridView
● ListView
Here is how Views and ViewGroups are linked:

Now we’ll move towards the Android layouts:

What is Android Layout?

Layout basically refers to the arrangement of elements on a page these elements are likely to be images,
texts or styles. They define the structure of android user interface in the app, like in an activity. All
elements in the layout are built with the help of Views and ViewGroups. These layouts can have various
widgets like buttons, labels, textboxes, and many others.
We can define a Layout as follows:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

android:id="@+id/layout2"

android:layout_width="match_parent"

android:layout_height="match_parent"
android:layout_weight="1"

android:background="#8ED3EB"

android:gravity="center"

android:orientation="vertical" >

<TextView

android:id="@+id/textView4"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginLeft="10dp"

android:layout_marginTop="-40dp"

android:fontFamily="@font/almendra_bold"

android:text="This is a TextView" />

</LinearLayout>

Attributes of Layout in Android

The following are the attributes for customizing a Layout while defining it:

● android:id: It uniquely identifies the Android Layout.


● android:hint: It shows the hint of what to fill inside the EditText.
● android:layout_height: It sets the height of the layout.
● android:layout_width: It sets the width of the layout.
● android:layout_gravity: It sets the position of the child view.
● android:layout_marginTop: It sets the margin of the from the top of the layout.
● android:layout_marginBottom: It sets the margin of the from the bottom of the layout.
● android:layout_marginLeft: It sets the margin of the from the left of the layout.
● android:layout_marginRight: It sets the margin of the from the right of the layout.
● android:layout_x: It specifies the x coordinates of the layout.
● android:layout_y: It specifies the y coordinates of the layout.
Types of Layouts in Android

Now that we’ve learned about the view and view groups and also somewhat about the layouts.
Subsequently let us see the types of Layouts in Android, that are as follows:

● Linear Layout
● Relative Layout
● Constraint Layout
● Table Layout
● Frame Layout
● List View
● Grid View
● Absolute Layout
● WebView
● ScrollView
These are the types of layouts and out of them we’ll learn about the two very important layouts:

1. Linear Layout

We use this layout to place the elements in a linear manner. A Linear manner means one element per
line. This layout creates various kinds of forms on Android. In this, arrangement of the elements is in a
top to bottom manner.

This can have two orientations:


a. Vertical Orientation – It is shown above where the widgets such as TextViews, and all in a vertical
manner.
b. Horizontal Orientation – It is shown above where the widgets such as TextViews, and all in a
horizontal manner.
2. Relative Layout

This layout is for specifying the position of the elements in relation to the other elements that are
present there.

In the relative layout, alignment of the position of the elements to the parent container is possible. To
define it in such a way, we write the following:

● android:layout_alignParentTop= “true”
● android:layout_alignParentLeft= “true”
If we write the above code, the element will get aligned on the top left of the parent container.

If we want to align it with some other element in the same container, it can be defined is as follows:

● android:layout_alignLeft= “@+id/element_name”
● android:layout_below= “@+id/element_name”
This will align the element below the other element to its left.

Here are the pictorial representations of different layouts-


Android LinearLayout is a view group that aligns all children in either vertically or horizontally.

Linear Layout

LinearLayout Attributes
Following are the important attributes specific to LinearLayout −

Sr.No Attribute & Description

android:id
1
This is the ID which uniquely identifies the layout.

android:baselineAligned
2
This must be a boolean value, either "true" or "false" and prevents the layout from aligning its children's baselines.

android:baselineAlignedChildIndex
3
When a linear layout is part of another layout that is baseline aligned, it can specify which of its children to baseline
align.
android:divider
4
This is drawable to use as a vertical divider between buttons. You use a color value, in the form of "#rgb", "#argb",
"#rrggbb", or "#aarrggbb".

android:gravity
5
This specifies how an object should position its content, on both the X and Y axes. Possible values are top, bottom,
left, right, center, center_vertical, center_horizontal etc.

android:orientation
6
This specifies the direction of arrangement and you will use "horizontal" for a row, "vertical" for a column. The
default is horizontal.

Following is the content of the modified main activity file src/com.example.demo/MainActivity.java.


This file can include each of the fundamental lifecycle methods.

package com.example.demo;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {


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

Following will be the content of res/layout/activity_main.xml file −

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button android:id="@+id/btnStartService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="start_service"/>
<Button android:id="@+id/btnPauseService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="pause_service"/>

<Button android:id="@+id/btnStopService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="stop_service"/>

</LinearLayout>

Following will be the content of res/values/strings.xml to define two new constants −

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>

Let's try to run our modified Hello World! application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio, open one of your
project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD
and starts it and if everything is fine with your setup and application, it will display following Emulator
window −

Now let's change the orientation of Layout as android:orientation="horizontal" and try to run the same
application, it will give following screen −
Android RelativeLayout enables you to specify how child views are positioned relative to each other. The
position of each view can be specified as relative to sibling elements or relative to the parent.

Relative Layout

RelativeLayout Attributes
Following are the important attributes specific to RelativeLayout −
Sr.No. Attribute & Description

1
android:id
This is the ID which uniquely identifies the layout.

2
android:gravity
This specifies how an object should position its content, on both the X and Y axes. Possible values are top, botto
left, right, center, center_vertical, center_horizontal etc.

3
android:ignoreGravity
This indicates what view should not be affected by gravity.

Using RelativeLayout, you can align two elements by right border, or make one below another, centered
in the screen, centered left, and so on. By default, all child views are drawn at the top-left of the layout,
so you must define the position of each view using the various layout properties available
from RelativeLayout.LayoutParams and few of the important attributes are given below −

Attribute & Description

android:layout_alignBottom
Makes the bottom edge of this view match the bottom edge of the given anchor view ID and must be a reference
to another resource, in the form "@[+][package:]type:name".

android:layout_alignLeft
Makes the left edge of this view match the left edge of the given anchor view ID and must be a reference to
another resource, in the form "@[+][package:]type:name".

android:layout_alignParentBottom
If true, makes the bottom edge of this view match the bottom edge of the parent. Must be a boolean value, either
"true" or "false".

android:layout_alignParentEnd
If true, makes the end edge of this view match the end edge of the parent. Must be a boolean value, either "true"
or "false".

android:layout_alignParentLeft
If true, makes the left edge of this view match the left edge of the parent. Must be a boolean value, either "true"
or "false".

android:layout_alignParentRight
If true, makes the right edge of this view match the right edge of the parent. Must be a boolean value, either
"true" or "false".

android:layout_alignParentStart
If true, makes the start edge of this view match the start edge of the parent. Must be a boolean value, either
"true" or "false".

android:layout_alignParentTop
If true, makes the top edge of this view match the top edge of the parent. Must be a boolean value, either "true"
or "false".

android:layout_alignRight
Makes the right edge of this view match the right edge of the given anchor view ID and must be a reference to
another resource, in the form "@[+][package:]type:name".

android:layout_alignStart
Makes the start edge of this view match the start edge of the given anchor view ID and must be a reference to
another resource, in the form "@[+][package:]type:name".

android:layout_alignTop
Makes the top edge of this view match the top edge of the given anchor view ID and must be a reference to
another resource, in the form "@[+][package:]type:name".

android:layout_below
Positions the top edge of this view below the given anchor view ID and must be a reference to another resource, in
the form "@[+][package:]type:name".

android:layout_centerHorizontal
If true, centers this child horizontally within its parent. Must be a boolean value, either "true" or "false".

android:layout_centerInParent
If true, centers this child horizontally and vertically within its parent. Must be a boolean value, either "true" or
"false".

android:layout_centerVertical
If true, centers this child vertically within its parent. Must be a boolean value, either "true" or "false".

android:layout_toEndOf
Positions the start edge of this view to the end of the given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".

android:layout_toLeftOf
Positions the right edge of this view to the left of the given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".

android:layout_toRightOf
Positions the left edge of this view to the right of the given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".

android:layout_toStartOf
Positions the end edge of this view to the start of the given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".

package com.example.demo;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {


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

Following will be the content of res/layout/activity_main.xml file −

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >

<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentStart="true"
android:layout_below="@+id/name">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button2" />

</LinearLayout>

</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new constants −

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="action_settings">Settings</string>
<string name="reminder">Enter your name</string>
</resources>

ndroid TableLayout going to be arranged groups of views into rows and


columns. You will use the <TableRow> element to build a row in the table.
Each row has zero or more cells; each cell can hold one View object.
TableLayout containers do not display border lines for their rows, columns, or
cells.
TableLayout Attributes
Following are the important attributes specific to TableLayout −

Sr Attribute & Description


.N
o.

1
android:id
This is the ID which uniquely identifies the layout
.

2
android:collapseColumns
This specifies the zero-based index of the columns to collapse. The column indices mu
be separated by a comma: 1, 2, 5.collapse columns attribute is used to collapse or invisible t
column’s of a table layout. These columns are the part of the table information but are invisible.
If the values is 0 then the first column appears collapsed, i.e it is the part of table but it is invisible.

3
android:shrinkColumns
The zero-based index of the columns to shrink. The column indices must be separated b
a comma: 1, 2, 5.

4
android:stretchColumns
The zero-based index of the columns to stretch. The column indices must be separated b
a comma: 1, 2, 5.

Example
This example will take you through simple steps to show how to create your
own Android application using Table Layout. Follow the following steps to
modify the Android application we created in Hello World Example chapter −

Ste Description
p

1 You will use Android Studio IDE to create an Android application and name it as demo unde
a package com.example.demo as explained in the Hello World Example chapter.

2 Modify the default content of res/layout/activity_main.xml file to include few widgets in table
layout.

3 No need to modify string.xml, Android studio takes care of default constants

4 Run the application to launch Android emulator and verify the result of the changes done in
the application.

Following is the content of the modified main activity


file src/com.example.demo/MainActivity.java. This file can include each of
the fundamental lifecycle methods.
package com.example.demo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {


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

}
Following will be the content of res/layout/activity_main.xml file −
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:text="Time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />

<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textClock"
android:layout_column="2" />

</TableRow>

<TableRow>

<TextView
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="200px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>

<TableRow>

<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />

<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>

<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ratingBar"
android:layout_column="2" />
</TableRow>

<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>

<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="@+id/button"
android:layout_column="2" />
</TableRow>

</TableLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>
Let's try to run our modified Hello World! application we just modified. I
assume you had created your AVD while doing environment setup. To run the
app from Android Studio, open one of your project's activity files and click
Run icon from the toolbar. Android studio installs the app on your AVD and
starts it and if everything is fine with your setup and application, it will display
following Emulator window −
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.

Sr.N Attribute & Description


o

1
android:id
This is the ID which uniquely identifies the layout.

2
android:foreground

This defines the drawable to draw over the content and possible values may

be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

3
android:foregroundGravity

Defines the gravity to apply to the foreground drawable. The gravity defaults

to fill. Possible values are top, bottom, left, right, center, center_vertical,

center_horizontal etc.

4
android:measureAllChildren

Determines whether to measure all children or just those in the VISIBLE or

INVISIBLE state when measuring. Defaults to false.

package com.example.demo;

import android.os.Bundle;

import android.app.Activity;

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}

Following will be the content of res/layout/activity_main.xml file −

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<ImageView

android:src="@drawable/ic_launcher"

android:scaleType="fitCenter"

android:layout_height="250px"

android:layout_width="250px"/>

<TextView

android:text="Frame Demo"

android:textSize="30px"

android:textStyle="bold"

android:layout_height="fill_parent"

android:layout_width="fill_parent"

android:gravity="center"/>

</FrameLayout>

Following will be the content of res/values/strings.xml to define two new constants −

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="app_name">demo</string>

<string name="action_settings">Settings</string>

</resources>
Let's try to run our modified Hello World! application we just modified. I assume you

had created your AVD while doing environment setup. To run the app from Android

Studio, open one of your project's activity files and click Run icon from the toolbar.

Android Studio installs the app on your AVD and starts it and if everything is fine with

your setup and application, it will display following Emulator window −

You might also like