A layout defines the structure for a user interface in your app, such as in an activity.
All elements
in the layout are built using a hierarchy of View and ViewGroup objects. A View usually draws
something the user can see and interact with. Whereas a ViewGroup is an invisible container
that defines the layout structure for View and other ViewGroup objects, as shown in figure 1.
Figure 1. Illustration of a view hierarchy, which defines a UI layout
The View objects are usually called "widgets" and can be one of many subclasses, such
as Button or TextView. The ViewGroup objects are usually called "layouts" and can be one of
many types that provide a different layout structure, such as LinearLayout or ConstraintLayout .
You can declare a layout in two ways:
Declare UI elements in XML. Android provides a straightforward XML vocabulary that
corresponds to the View classes and subclasses, such as those for widgets and layouts.
You can also use Android Studio's Layout Editor to build your XML layout using a drag-
and-drop interface.
Instantiate layout elements at runtime. Your app can create View and ViewGroup
objects (and manipulate their properties) programmatically.
Write the XML
Using Android's XML vocabulary, you can quickly design UI layouts and the screen
elements they contain, in the same way you create web pages in HTML — with a series
of nested elements.
Each layout file must contain exactly one root element, which must be a View or
ViewGroup object. Once you've defined the root element, you can add additional layout
objects or widgets as child elements to gradually build a View hierarchy that defines
your layout. For example, here's an XML layout that uses a vertical LinearLayout to hold
a TextView and a Button:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
After you've declared your layout in XML, save the file with the .xml extension, in your
Android project's res/layout/ directory, so it will properly compile.
Load the XML Resource
ou should load the layout resource from your app code, in
your Activity.onCreate() callback implementation. Do so by calling setContentView(),
passing it the reference to your layout resource in the form of: R.layout.layout_file_name
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
Attributes
Some attributes are specific to a View object (for example, TextView supports
the textSize attribute)
android:id="@+id/my_button"
Layout Parameters
Every ViewGroup class implements a nested class that
extends ViewGroup.LayoutParams. This subclass contains property types that define the
size and position for each child view, as appropriate for the view group.
wrap_content tells your view to size itself to the dimensions required by its content.
match_parent tells your view to become as big as its parent view group will allow.
The basic implementation of list fragment is for creating list of items in
fragments.
A fragment that displays a list of items by binding to a data source such as an array
or Cursor, and exposes event handlers when the user selects an item.
ListFragment hosts a ListView object that can be bound to different data sources,
typically either an array or a Cursor holding query results.
public class ListFragment extends Fragment
java.lang.Object
android.app.Fragment
android.app.ListFragment
You will use Android Studio to create an Android application and
name it as SimpleListFragment under a
1
package com.example.tutorialspoint7.myapplication, with blank
Activity.
Modify the string file, which has placed at res/values/string.xml to
2
add new string constants
Create a layout called list_fragment.xml under the
3 directory res/layout to define your list fragments. and add fragment
tag(<fragment>) to your activity_main.xml
Create a myListFragment.java, which is placed
4
at java/myListFragment.java and it
contained onCreateView(),onActivityCreated() and OnItemClickListen
er()
Run the application to launch Android emulator and verify the result
5 of the changes done in the application.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ListFragmentDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="imgdesc">imgdesc</string>
<string-array name="Planets">
<item>Sun</item>
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
it contained linear layout and fragment tag.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/andro
id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/fragment1"
android:name="com.example.tutorialspoint7.myapplication
.MyListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
it contained linear layout,list view and text view
</resources>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
</LinearLayout>
Steps to follow:
Create a class MyListFragment and extend it to ListFragment.
Inside the onCreateView() method , inflate the view with above
defined list_fragment xml layout.
Inside the onActivityCreated() method , create a arrayadapter from
resource ie using String array R.array.planet which you can find
inside the string.xml and set this adapter to listview and also set
the onItem click Listener.
Inside the OnItemClickListener() method , display a toast message
with Item name which is being clicked.
package com.example.tutorialspoint7.myapplication;
import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MyListFragment extends ListFragment implements
OnItemClickListener {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment,
container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter =
ArrayAdapter.createFromResource(getActivity(),
R.array.Planets,
android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position,long id) {
Toast.makeText(getActivity(), "Item: " + position,
Toast.LENGTH_SHORT).show();
}
}
Following code will be the content of MainActivity.java
package com.example.tutorialspoint7.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
following code will be the content of manifest.xml, which has
placed at res/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/andro
id"
package="com.example.tutorialspoint7.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
UNIT-3
Android SDK versions
Android 15 (API level 35) June 2024
Android 14 (API level 34) June 2023
Android 13 (API level 33) June 2022
Android 12 (API levels 31, 32) March 2022
Android 12 (API level 31) August 2021
Structure of main.xml for Screen Layouts
Below is a basic example of a main.xml file that contains common UI elements.
Example 1: A Simple Layout with TextView and Button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" //refers to whether the screen is in portrait or
landscape mode.
android:padding="16dp"> //the space between the borders of an element and the
actual view component
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="18sp" />
//density-independent pixels (dp) and scalable pixels (sp) are units used to build layouts
and fonts that work across different screen densities, sizes, and aspect ratios:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
Key Components:
1. Root Layout (LinearLayout):
o The root layout here is a LinearLayout, which arranges its child views in a
single column or row, depending on the android:orientation attribute.
o android:layout_width="match_parent" ensures that the layout takes the
full width of the screen.
o android:layout_height="match_parent" does the same for height.
2. TextView:
o Displays a simple "Hello, World!" message.
o android:textSize adjusts the font size.
3. Button:
o A simple button labeled "Click Me".
o You can add logic to this button in the Kotlin/Java code of your activity.
How to Integrate main.xml with the Activity
In your Activity's Kotlin or Java file, you load the layout using setContentView().
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main) // This links to res/layout/main.xml
}
}
LinearLayout is a simple and easy-to-use layout for stacking UI elements.
ConstraintLayout offers more control and flexibility, particularly for more complex
layouts.
1. Layouts: Organizing UI Elements
Layouts are containers that hold and organize UI components (widgets). Android provides
several layout types, such as:
LinearLayout: Arranges its children in a single row or column.
RelativeLayout: Allows positioning of its children relative to each other or the
parent.
ConstraintLayout: Provides more flexible positioning with constraints.
FrameLayout: Designed to block out an area on the screen to display a single view.
TableLayout: Organizes UI components into rows and columns.
2. Widgets: The Building Blocks
Widgets are the individual UI elements (like buttons, text fields, etc.) you place inside
layouts.
Common Android Widgets:
TextView: Used to display text to the user.
EditText: A user input field where text can be entered.
Button: A clickable button to trigger actions.
ImageView: Displays an image resource.
CheckBox: A toggleable option that allows the user to select or deselect.
RadioButton: A single choice option from a group.
Switch/ToggleButton: A switch for turning settings on/off.
Using Graphical Layout Tools
Faster Prototyping: Quickly design and adjust layouts visually without writing XML
manually.
Real-Time Feedback: Immediate visual feedback on how your layout looks on
various screen sizes and orientations.
Reduced Errors: Automatically generates correct XML code, reducing human error
in code writing.
Ease of Constraint Management: Managing constraints in ConstraintLayout is much
easier with the drag-and-drop interface than manually typing out the constraints in
XML.
The Graphical Layout Tools in Android Studio streamline the process of designing
user interfaces. Using the Layout Editor, you can visually place and organize
widgets, configure their properties, and preview the layout in different device
configurations. This saves time and allows for quicker iterations in your UI design
process.
XML layout attributes
In Android, XML layout attributes define the properties and behavior of UI
components within a layout. These attributes are used to control the appearance, size,
position, and behavior of widgets such as TextView, Button, ImageView, and
layouts like LinearLayout, ConstraintLayout, etc.
Here’s a breakdown of some of the most commonly used XML layout attributes and
their purpose:
1. Basic Layout Attributes (for All Views)
These attributes are fundamental and are typically applied to any UI element (such as View,
TextView, Button, etc.).
android:layout_width:
o Specifies the width of the view.
o Possible values:
match_parent: The view should be as wide as its parent.
wrap_content: The view should be only as wide as its content.
Specific dimension (e.g., 200dp).
android:layout_height:
o Specifies the height of the view.
o Possible values: match_parent, wrap_content, specific dimensions
(e.g., 100dp).
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Me" />
2. View Positioning Attributes
These attributes help control how a view is positioned within a parent layout.
android:layout_margin:
o Specifies the space outside the view. It creates space between the view and its
parent or other views.
o You can specify margins for all sides (layout_margin) or for individual sides
(layout_marginStart, layout_marginEnd, layout_marginTop,
layout_marginBottom).
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_margin="16dp" />
3. Text-Related Attributes
These attributes apply to text-based views like TextView, EditText, and Button.
android:text:
o Specifies the text to be displayed by the view.
android:textSize:
o Specifies the size of the text. It's usually defined in sp (scale-independent
pixels).
android:textColor:
o Specifies the color of the text. You can use a hex code (e.g., #FF0000 for red)
or a color resource.
android:textStyle:
o Specifies the style of the text (e.g., bold, italic).
android:gravity:
o Controls the alignment of text or content within the view (e.g., center, left,
right).
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome"
android:textSize="18sp"
android:textColor="#FF5722"
android:textStyle="bold"
android:gravity="center" />
4. Layout-Specific Attributes
Each layout type (e.g., LinearLayout, ConstraintLayout) may have its own set of attributes
for controlling how child views are arranged within them.
LinearLayout Specific Attributes
android:orientation:
o Defines whether the views inside a LinearLayout are arranged horizontally or
vertically.
o Values: horizontal, vertical.
android:layout_weight:
o Used to define how much space a child view should take up relative to others
in a LinearLayout.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"//how much extra space to be allocated to the view
android:text="Item 1" />
</LinearLayout>
ConstraintLayout Specific Attributes
app:layout_constraintTop_toTopOf:
o Constrains the top of a view to the top of another view or the parent.
app:layout_constraintBottom_toBottomOf:
o Constrains the bottom of a view to the bottom of another view or the parent.
app:layout_constraintStart_toStartOf:
o Constrains the start (left in LTR mode) of a view to another view or parent.
app:layout_constraintEnd_toEndOf:
o Constrains the end (right in LTR mode) of a view to another view or parent.
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
5. Visibility and Behavior Attributes
android:visibility:
o Controls the visibility of a view.
o Values:
visible: The view is visible.
invisible: The view is not visible but still occupies space.
gone: The view is hidden and doesn’t occupy any space.
android:clickable:
o Specifies whether a view is clickable. For example, a Button should be
clickable, but a TextView may not be by default.
android:enabled:
o Specifies whether a view is enabled or disabled (grayed out and non-clickable
if set to false).
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:visibility="visible"
android:clickable="true"
android:enabled="true" />
6. Background and Style Attributes
android:background:
o Specifies the background of the view, which can be a color, drawable, or
image.
android:elevation (API 21+):
o Adds elevation (z-depth) to the view, making it appear as if it’s casting a
shadow.
android:theme:
o Applies a theme or style to the view. Themes define a consistent look for the
UI across different views.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Styled Text"
android:background="@color/lightGray"
android:elevation="4dp" />
7. Input Attributes (for EditText)
android:hint:
o Text that appears in the EditText when it's empty.
android:inputType:
o Defines the type of input, such as text, number, email, password, etc.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"
android:inputType="textPersonName" />
Displaying List with List fragments:
ListFragment - Android Developers
Creating dynamic and interactive lists is fundamental in Android development.
1. Creating List Fragments(represents reusable part of an app’s user interface)
A ListFragment is a fragment that displays a list of items by binding to a data source such as
an array or Cursor. It simplifies the process of creating a list within a fragment.
public class MyListFragment extends ListFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize data source
String[] items = {"Item 1", "Item 2", "Item 3"};
// Set up the adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, items);
setListAdapter(adapter);
}
}
2. Utilizing ListView and ArrayAdapter
A ListView is a view group that displays a list of scrollable items. An ArrayAdapter bridges
the gap between a data source (like an array) and the ListView.
// In your activity or fragment
ListView listView = findViewById(R.id.list_view);
String[] items = {"Item A", "Item B", "Item C"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
3. Customizing List Items
To create a more complex list item, define a custom layout and use a custom adapter.
Step 1: Define the Custom Layout (res/layout/custom_list_item.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/item_image"
android:src="@drawable/ic_item"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginRight="10dp" />
<TextView
android:id="@+id/item_text"
android:text="Item Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
4. Creating a Dialog Fragment
A DialogFragment displays a dialog window floating on top of its activity's window.
public class MyDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Exit the app
getActivity().finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Dismiss the dialog
dialog.dismiss();
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
parsing data between two fragments
To parse data between two fragments in Android, you typically use the Bundle object and the
fragment manager. Here’s how you can send data from one fragment to another:
Step-by-Step Guide
1. Sending Data from Fragment A to Fragment B
Fragment A: Prepare the data, store it in a Bundle, and set the arguments for
Fragment B.
// Fragment A (Sender)
public class FragmentA extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
// Create a button click listener to send data
Button button = view.findViewById(R.id.send_data_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create new instance of Fragment B
FragmentB fragmentB = new FragmentB();
// Create a Bundle to pass the data
Bundle bundle = new Bundle();
bundle.putString("key", "Hello from Fragment A");
// Set the arguments for Fragment B
fragmentB.setArguments(bundle);
// Replace Fragment A with Fragment B
FragmentManager fragmentManager =
getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragmentB);
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
2. Receiving Data in Fragment B
Fragment B: Retrieve the data sent by Fragment A from the Bundle.
// Fragment B (Receiver)
public class FragmentB extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
// Retrieve the arguments passed from Fragment A
Bundle bundle = getArguments();
if (bundle != null) {
String receivedData = bundle.getString("key");
// Display the received data
TextView textView = view.findViewById(R.id.received_data_textview);
textView.setText(receivedData);
}
return view;
}
}
Bundle: A Bundle is used to pass data between fragments. You store data using methods like
putString(), putInt(), etc., and retrieve it with getString(), getInt(), etc.
Fragment Transaction: This replaces Fragment A with Fragment B. The
addToBackStack(null) method ensures that when the user presses the back button, they return
to Fragment A.
TextView handles fragment transactions like adding, removing, or replacing fragments.