[Go to site: main page, start]

0% found this document useful (0 votes)
51 views32 pages

Android UI Measurements and Layouts Guide

Synopsis

Uploaded by

pavansabaloor
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views32 pages

Android UI Measurements and Layouts Guide

Synopsis

Uploaded by

pavansabaloor
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-II

Measurements in Android UI
When designing Android apps, screen sizes and pixel densities vary across devices (small
phones, tablets, large screens). To make UIs look consistent, Android provides device and
pixel density–independent units:

🔹 Common Measurement Units


1. px (pixels)

 Actual pixels on the screen.

 Not recommended, since different devices have different pixel densities.

2. dp (density-independent pixels)

 Recommended unit for layout dimensions (width, height, margins).

 Adjusts automatically to different screen densities.

 1 dp = 1 pixel on a 160 dpi screen.

3. sp (scale-independent pixels)

 Similar to dp, but also scales according to user’s font size preference.

 Recommended for text sizes.

4. pt (points)

 1 pt = 1/72 of an inch, not often used in Android.

5. in (inches) & mm (millimeters)

 Physical measurements, rarely used.

Layouts in Android
A Layout defines how UI elements (Views like Buttons, TextViews, etc.) are arranged on the
screen.

🔹 (a) Linear Layout


 Arranges child views in a single row or column.

 Orientation can be horizontal or vertical.

 Example: A vertical list of buttons.

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"/>
</LinearLayout>

🔹 (b) Relative Layout


 Positions child views relative to parent or other views.

 Example: Place a button below a TextView, or align a view to the right of another.

 More flexible but complex than LinearLayout.

<RelativeLayout

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello Text"

android:textSize="18sp"

android:layout_centerHorizontal="true"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me"

android:layout_below="@id/textView"

android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"/>

</RelativeLayout>

🔹 (c) Grid Layout


 Arranges views in a grid (rows & columns), like a table.

 Each cell can hold one view (or span multiple).

 Good for calculator apps, photo galleries.

<GridLayout

android:layout_width="match_parent"

android:layout_height="match_parent"

android:rowCount="2"

android:columnCount="2"

android:alignmentMode="alignMargins"

android:useDefaultMargins="true">

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="1"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="2"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="3"/>

<Button

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="4"/>

</GridLayout>

🔹 (d) Table Layout


 Organizes content into rows and columns like an HTML table.

 Each row is a TableRow.

 Often used for forms, structured data.

<TableLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:stretchColumns="1">

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Name:"/>

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

</TableRow>

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Email:"/>

<EditText
android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

</TableRow>

<TableRow>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"/>

</TableRow>

</TableLayout>

User interface Components

📝 Editable UI Components
Definition: Editable UI components are those which allow the user to enter data,
make selections, or modify the state of the component. They are interactive and
capture user input.

Examples:

 EditText → user types text.


 CheckBox → user selects multiple options.
 RadioButton → user selects one option from a group.
 ToggleButton / Switch → user changes state ON/OFF.
 Spinner → user selects an item from a dropdown list.
 DatePicker / TimePicker → user selects date or time.

✍️1. EditText
 What it is: A text input field.
 Purpose: Allows the user to type and enter data.
 Where used: Forms, login screens, search bars.
 Examples:
 Entering Name
 Entering Email
 Entering Password

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter your name"/>

☑️2. CheckBox
 What it is: A small square box that can be checked or unchecked.
 Purpose: Lets the user select multiple options at the same time.
 Where used: Preferences, survey forms, multi-choice questions.
 Examples:
 Select hobbies: Reading, Music, Sports
 Choose topics: Math, Science, English

<CheckBox

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="I agree"/>

🔘 3. RadioButton (inside RadioGroup)


 What it is: A round button that allows only one option to be selected at a
time.
 Purpose: Used for single-choice questions.
 Where used: Forms, surveys, settings.
 Examples:
 Select Gender → Male / Female
 Choose Payment Method → Credit Card / UPI / Cash

<RadioGroup

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:orientation="vertical">

<RadioButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Male"/>

<RadioButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Female"/>

</RadioGroup>

🔀 4. ToggleButton / Switch
 What it is: A two-state button that represents ON / OFF or Enabled /
Disabled.
 Purpose: Used for quick settings and preferences.
 Where used: App settings, control panels.
 Examples:
 Wi-Fi ON / OFF
 Bluetooth ON / OFF

<ToggleButton

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:textOn="WiFi ON"

android:textOff="WiFi OFF"/>

<Switch

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Bluetooth"/>

⬇️5. Spinner (Dropdown Menu)


 What it is: A compact list of options that expands when clicked.
 Purpose: Saves screen space and allows the user to pick one option.
 Where used: Forms, registrations, country/state selection.
 Examples:
 Select Country → India / USA / UK
 Choose Language → English / Hindi / Spanish

<Spinner

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

📅⏰ 6. Pickers (DatePicker & TimePicker)


 What it is: Special UI components to select date or time.
 Purpose: Helps the user input valid date/time easily.
 Where used: Booking apps, reminders, scheduling apps.
 Examples:
 DatePicker → Select date of birth, appointment date.
 TimePicker → Select meeting time, alarm time.

<DatePicker

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>
📌 Non-Editable UI Components
Definition: Non-editable UI components are those which only display information or
perform a predefined action when clicked. Users cannot directly change their
content.

Example:

 TextView → displays static text.


 Button → triggers an action but cannot be edited.
 Dialog → shows a message or confirmation popup.

📝 1. TextView

 What it is: A simple UI element that only displays text on the screen.

 Editable? ❌ No, users cannot change it.

 Purpose: To show labels, instructions, or messages to the user.

 Examples:

 "Welcome to the App"

 "Enter your Name:" (label before an input field)

 "Result: Passed"

<TextView
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Welcome to the App"

android:textSize="18sp"/>

🔘 2. Button

 What it is: A clickable component that performs an action when pressed.

 Editable? ❌ No, users cannot type or modify it.

 Purpose: To trigger some functionality.

 Examples:

 Login button → takes you to the home screen.

 Submit button → sends form data.

 Next button → moves to the next screen.

<Button

android:id="@+id/btnSubmit"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"/>

val btn: Button = findViewById([Link])

[Link] {

// Action when button is clicked

}
💬 3. Dialog

 What it is: A popup window that appears on top of the screen.


 Editable? ❌ No, it only shows messages or asks for confirmation
(though the user can respond by pressing Yes/No).

 Purpose: To alert the user, show important info, or confirm an action.

 Examples:

 Exit confirmation → “Are you sure you want to exit?”

 Warning → “Low battery!”

 Information → “Update successful.”

[Link](this)

.setTitle("Exit")

.setMessage("Are you sure you want to exit?")

.setPositiveButton("Yes") { _, _ ->

// Action on Yes

.setNegativeButton("No", null)

.show()

🎯 What Is Event Handling?


In Android, the UI is event-driven.

 Events = user interactions like taps, clicks, swipes, typing text, toggling
switches, selecting from a list.
 Event Handling = writing code that responds to those interactions.

Every View (Button, TextView, EditText, etc.) can generate events, and you attach
listeners to handle them.

OR

Events are the actions performed by the user in order to interact with the
application, for e.g. pressing a button or touching the screen. The events
are managed by the android framework in the FIFO manner i.e. First In -
First Out. Handling such actions or events by performing the desired task is
called Event Handling

Overview of the input event management

Event Listeners: It is an interface in the View class. It contains a single callback


method. Once the view to which the listener is associated is triggered due to user
interaction, the callback methods are called.

Event Handlers: It is responsible for dealing with the event that the event listeners
registered for and performing the desired action for that respective event.

Event Listeners Registration: Event Registration is the process in which an Event


Handler gets associated with an Event Listener so that this handler is called when
the respective Event Listener fires the event.

Touch Mode: When using an app with physical keys it becomes necessary to give
focus to buttons on which the user wants to perform the action but if the device is
touch-enabled and the user interacts with the interface by touching it, then it is no
longer necessary to highlight items or give focus to particular View. In such cases,
the device enters touch mode and in such scenarios, only those views for which the
isFocusableInTouchMode() is true will be focusable, e.g. plain text widget.

For e.g. if a button is pressed then this action or event gets registered by the event
listener and then the task to be performed by that button press is handled by the
event handler, it can be anything like changing the color of the text on a button press
or changing the text itself, etc.

🖱 1. Handling Click Events

Example: Button Click

<Button

android:id="@+id/myButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me" />

Button myButton = findViewById([Link]);

// Option 1: Using OnClickListener

[Link](new [Link]() {

@Override

public void onClick(View v) {

[Link]([Link], "Button clicked!",


Toast.LENGTH_SHORT).show();

});

👉 You can also assign directly in XML:

android:>

and in Activity:

public void myButtonClick(View v) {


[Link](this, "Clicked via XML!", Toast.LENGTH_SHORT).show();

🔄 2. Handling State Change Events

Checkbox

CheckBox checkBox = findViewById([Link]);

[Link](new
[Link]() {

@Override

public void onCheckedChanged(CompoundButton buttonView, boolean


isChecked) {

if (isChecked) {

[Link]([Link], "Checked!",
Toast.LENGTH_SHORT).show();

} else {

[Link]([Link], "Unchecked!",
Toast.LENGTH_SHORT).show();

});

Radio Buttons / RadioGroup

RadioGroup radioGroup = findViewById([Link]);

[Link](new
[Link]() {
@Override

public void onCheckedChanged(RadioGroup group, int checkedId) {

if (checkedId == [Link]) {

[Link]([Link], "Yes selected",


Toast.LENGTH_SHORT).show();

});

Toggle Button / Switch

ToggleButton toggle = findViewById([Link]);

[Link]((buttonView, isChecked) -> {

if (isChecked) {

[Link](this, "ON", Toast.LENGTH_SHORT).show();

} else {

[Link](this, "OFF", Toast.LENGTH_SHORT).show();

});

📋 3. Handling Selection Events

Spinner (Dropdown)

Spinner spinner = findViewById([Link]);

[Link](new
[Link]() {
@Override

public void onItemSelected(AdapterView<?> parent, View view, int


position, long id) {

String item = [Link](position).toString();

[Link]([Link], "Selected: " + item,


Toast.LENGTH_SHORT).show();

@Override

public void onNothingSelected(AdapterView<?> parent) { }

});

⌨️4. Handling Text Input Changes

EditText with TextWatcher

EditText editText = findViewById([Link]);

[Link](new TextWatcher() {

@Override

public void beforeTextChanged(CharSequence s, int start, int count, int


after) { }

@Override

public void onTextChanged(CharSequence s, int start, int before, int


count) {

// Triggered while typing

@Override

public void afterTextChanged(Editable s) {


[Link]([Link], "You typed: " + [Link](),
Toast.LENGTH_SHORT).show();

});

🧩 1. What Is a Fragment?

 A Fragment is a modular section of an Activity.


 Think of it as a mini-Activity that has:
 Its own UI layout
 Its own lifecycle methods
 Its own logic
 Multiple Fragments can exist inside a single Activity (useful for tablets, multi-
pane UIs).
 Fragments make UIs more reusable, dynamic, and flexible

In Android, the fragment is the part of the Activity that represents a portion of the
User Interface(UI) on the screen. It is the modular section of the Android activity that
is very helpful in creating UI designs that are flexible in nature and auto-adjustable
based on the device screen size. The UI flexibility on all devices improves the user
experience and adaptability of the application. that can exist only inside an activity as
its lifecycle is dependent on the lifecycle of the host activity. For example, if the host
activity is paused, then all the methods and operations of the fragment related to that
activity will stop functioning, the fragment is also termed a sub-activity. Fragments in
Android can be added, removed, or replaced dynamically i.e., while the activity is
running.

<fragment> tag is used to insert the fragment in an android activity layout. By


dividing the activity's layout multiple fragments can be added in it.

Below is the pictorial representation of fragment interaction with the activity:


Types of Android Fragments

Single Fragment: Display only one single view on the device screen. This type of
fragment in android is mostly used for mobile phones.

List Fragment: This Fragment is used to display a list-view from which the user can
select the desired sub-activity. The menu drawer of apps like Gmail is the best
example of this kind of android fragment.

Fragment Transaction: This kind of fragments in android supports the transition


from one fragment in android to another at run time. Users can switch between
multiple fragments like switching tabs.

Steps to Create a Fragment

Step 1: Create a Fragment Class

We extend the Fragment class and override onCreateView() to define its


UI.

public class ExampleFragment extends Fragment {

@Nullable

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,


Bundle savedInstanceState) {
// Inflate the layout for this fragment

return [Link]([Link].fragment_example, container, false);

🔹 Explanation:

 onCreateView() → called when Android needs the Fragment’s UI.


 [Link]([Link].fragment_example, container, false) → loads
the XML layout for the fragment.

Step 2: Create a Fragment Layout (XML)

File: res/layout/fragment_example.xml

<LinearLayout
xmlns:android="[Link]

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center"

android:orientation="vertical">

<TextView

android:id="@+id/txtMessage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello from Fragment!"

android:textSize="20sp"

android:padding="16dp"/>
</LinearLayout>

Step 3: Add Fragment to an Activity

There are two ways:

(A) Static Fragment (via XML)

In activity_main.xml:

<fragment

android:id="@+id/exampleFragment"

android:name="[Link]"

android:layout_width="match_parent"

android:layout_height="wrap_content"/>

(B) Dynamic Fragment (via Java/Kotlin)

In [Link]:

FragmentManager fm = getSupportFragmentManager();

FragmentTransaction ft = [Link]();

[Link]([Link], new ExampleFragment());

[Link]();

And in your activity_main.xml define a container:

<FrameLayout

android:id="@+id/fragmentContainer"

android:layout_width="match_parent"

android:layout_height="match_parent"/>
🔄 3. Communicating with Activity

Fragments often need to interact with their host Activity.

Example: Access TextView in Fragment and change it:

TextView txt = getView().findViewById([Link]);

[Link]("Updated from Fragment!");

Or, define a listener interface to send events from Fragment → Activity.

Fragment lifecycle

The lifecycle events of a Fragment mirror those of its parent Activity;


however, after the containing Activity is in its active — resumed — state
adding or removing a Fragment will affect its lifecycle independently.
Fragments include a series of event handlers that mirror those in the
Activity class. They are triggered as the Fragment is created, started,
resumed, paused, stopped, and destroyed. Fragments also include a
number of additional callbacks that signal binding and unbinding the
Fragment from its parent Activity, creation (and destruction) of the
Fragment’s View hierarchy, and the completion of the creation of the
parent Activity.
Each fragment has its own lifecycle but due to the connection with the
Activity it belongs to, the android fragment lifecycle is influenced by the
activity's lifecycle.

Methods of the Android Fragment

Methods Description

The very first method to be called when the


fragment has been associated with the activity. This
method executes only once during the lifetime of a
fragment.
onAttach()
When we attach fragment(child) to Main(parent)
activity then it call first and then not call this method
any time(like you run an app and close and reopen)
simple means that this method call only one time.

This method initializes the fragment by adding all the


onCreate()
required attributes and components.

System calls this method to create the user interface


of the fragment. The root of the fragment's layout is
returned as the View component by this method to
onCreateView( draw the UI.
)
You should inflate your layout in onCreateView but
shouldn't initialize other views using findViewById in
onCreateView.

It indicates that the activity has been created in


onViewCreate
which the fragment exists. View hierarchy of the
d()
fragment also instantiated before this function call.
The system invokes this method to make the
onStart()
fragment visible on the user's device.

This method is called to make the visible fragment


onResume()
interactive.

It indicates that the user is leaving the fragment.


onPause() System call this method to commit the changes
made to the fragment.

Method to terminate the functioning and visibility of


onStop()
fragment from the user's screen.

System calls this method to clean up all kinds of


onDestroyView resources as well as view hierarchy associated with
() the fragment. It will call when you can attach new
fragment and destroy existing fragment Resoruce

It is called to perform the final clean up of fragment's


onDestroy()
state and its lifecycle.

The system executes this method to disassociate the


fragment from its host activity.
onDetach()
It will call when your fragment Destroy(app crash or
attach new fragment with existing fragment)
Example of Android Fragment

Fragments in android are always embedded in Activities i.e., they are


added to the layout of activity in which they reside. Multiple fragments
can be added to one activity. This task can be carried out in 2 ways:

Statically: Explicitly mention the fragment in the XML file of the activity.
This type of fragment can not be replaced during the run time.

Dynamically: FragmentManager is used to embed fragments with


activities that enable the addition, deletion, or replacement of fragments
at run time.

Almost all android apps use dynamic addition of fragments as it improves


the user experience. Below is the step-by-step implementation of adding 2
fragments in one activity. A default fragment will be visible when the
activity appears on the screen and the user can switch between the 2
fragments at the run time.

NOTE: For more detailed Explanation visit: Fragment Lifecycle in Android


- GeeksforGeeks

🧩 Fragment States in Android

Unlike Activities (which have a simpler lifecycle), Fragments have extra


states because their UI (View hierarchy) can be destroyed separately
while the Fragment object still exists.

🔄 1. The Major Fragment States

1. Active / Resumed

 Fragments are visible on screen and interactive.


 It’s tied to the Activity’s resumed state.
 Example: A form fragment where the user is typing.

2. Paused

 Fragment is partially visible but not in focus.


 Users cannot interact with it.
 Example: A dialog fragment appears on top of your fragment.

3. Stopped

 Fragment is completely hidden, but the instance still exists in


memory.
 Its UI is intact, but not visible.
 Example: The user navigates to another Activity.

4. Destroyed View

 Fragment object still exists, but its UI (View hierarchy) is


destroyed.
 This happens when Android needs to free memory or when the
fragment goes to the back stack.
 Example: A fragment is replaced, but if you press Back, it will
recreate its UI.

5. Destroyed (Removed)

 Fragment is completely destroyed → both object and UI are gone.


 Happens after onDestroy() and onDetach().

🧭 2. State Transitions

Here’s how a Fragment moves between states:

onAttach() → onCreate() → onCreateView() → onActivityCreated()

→ onStart() → onResume() → (Active State)

When fragment is hidden or replaced:

onPause() → onStop() → onDestroyView() → (Stopped/Destroyed View)


When fragment is fully removed:

onDestroy() → onDetach() → (Destroyed)

Key Difference from Activity States

 Activity: When destroyed, both object + UI are gone.

 Fragment: Can destroy only its UI (onDestroyView) but keep the


Fragment object alive (helps with Back Stack navigation).

🧩 Adding Fragments to an Activity

Adding fragments to an Android activity can be achieved through two


primary methods: statically via XML layout or dynamically using the
FragmentManager.

1. Statically Adding Fragments via XML:

This method embeds the fragment directly within the activity's layout file.

Define the Fragment in XML: In your activity's layout file (e.g.,


activity_main.xml), use the <fragment> tag.

Code

<FrameLayout

android:id="@+id/fragment_container"

android:layout_width="match_parent"

android:layout_height="match_parent" />

<fragment

android:id="@+id/my_fragment"

android:name="[Link]" // Replace with


your fragment's full class name
android:layout_width="match_parent"

android:layout_height="match_parent" />

Create the Fragment Class: Create a Java or Kotlin class that extends
[Link].

public class MyFragment extends Fragment {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup


container,

Bundle savedInstanceState) {

// Inflate the layout for this fragment

return [Link]([Link].fragment_my, container, false);

2. Dynamically Adding Fragments Programmatically:

This method allows for more control over fragment transactions at


runtime, such as adding, replacing, or removing fragments based on user
interaction or application logic.

Get FragmentManager: Obtain an instance of FragmentManager from your


activity (e.g., getSupportFragmentManager()).

Begin a FragmentTransaction: Initiate a transaction using


beginTransaction().

Add/Replace the Fragment: Use add() or replace() to place the fragment


within a container ViewGroup in your activity's layout.

// In your Activity's onCreate() or a method triggered by an event

if (savedInstanceState == null) {

getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)

.add([Link].fragment_container, [Link], null) // Use add()


for initial placement

.commit();

Commit the Transaction: Call commit() to execute the fragment


transaction.

Fragment Transactions: Adding, Removing, Replacing

Fragment transactions in Android allow for dynamic manipulation of


Fragments within an Activity's layout, enabling the creation of flexible and
responsive user interfaces. These operations are performed using the
FragmentManager and FragmentTransaction classes.

Core Operations:

Adding a Fragment:

This operation places a new Fragment into a designated container (e.g., a


FrameLayout) within the Activity's layout.

The add() method of FragmentTransaction is used, taking the container ID


and the Fragment instance as arguments.

Example:

FragmentManager fragmentManager =
getSupportFragmentManager();

FragmentTransaction transaction =
[Link]();

[Link]([Link].fragment_container, new MyFragment());

[Link]();

Removing a Fragment:
This operation detaches an existing Fragment from its container and
destroys its view hierarchy.

The remove() method of FragmentTransaction is used, taking the


Fragment instance to be removed as an argument.

Example:

FragmentManager fragmentManager =
getSupportFragmentManager();

FragmentTransaction transaction =
[Link]();

Fragment existingFragment =
[Link]([Link].my_fragment_id); // Or
findFragmentByTag()

if (existingFragment != null) {

[Link](existingFragment);

[Link]();

Replacing a Fragment:

This operation is a convenience method that combines the removal of an


existing Fragment and the addition of a new one within the same
container.

The replace() method of FragmentTransaction is used, taking the


container ID and the new Fragment instance as arguments.

Example:

FragmentManager fragmentManager =
getSupportFragmentManager();

FragmentTransaction transaction =
[Link]();
[Link]([Link].fragment_container, new
AnotherFragment());

[Link]();

🔗 Interfacing Between Fragments and Activities – Theory

🧩 Why Do Fragments Need Interfacing?

 A Fragment is modular → it should not tightly depend on the


Activity that hosts it.
 But in real apps, fragments often need to communicate:
 A Fragment → Activity: Example → “User clicked a button,
send data to Activity.”
 An Activity → Fragment: Example → “Update the fragment
UI when Activity receives data.”
 A Fragment → Fragment: Example → “ListFragment sends
selected item to DetailFragment.”

👉 To achieve this, we use interfaces and callbacks, instead of direct


references, to keep code modular and reusable.

📌 Fragment → Activity Communication

 Fragments don’t know which Activity they are in.


 To communicate, a Fragment defines an interface (a contract).
 The Activity implements this interface.
 When something happens inside the Fragment (like a button click),
it calls the method from the interface.
 The Activity receives the event and decides what to do.

👉 This ensures loose coupling between Fragment and Activity.

📌 Activity → Fragment Communication

 The Activity manages Fragments through the FragmentManager.


 It can directly call a public method of the Fragment to pass data.
 Example: Activity receives user input and updates the Fragment’s
TextView.
👉 Here the Activity is in control, because it is the host.

📌 Fragment → Fragment Communication

 Fragments never talk to each other directly (to avoid tight


coupling).
 Instead:
1. Fragment A sends data to Activity (via interface).
2. Activity receives it and passes it to Fragment B.

👉 This way, Fragments remain independent and reusable.

🎯 Why Use Interfaces Instead of Direct Access?

 Encourages modular design.


 A Fragment can be reused in multiple Activities.
 If Fragments directly accessed Activities (or each other), they would
become hard to maintain and reuse.
 Interfaces create a clear communication channel.

Multi-screen Activities

Android's multi-screen activities, or "multi-window" capabilities, allow


users to interact with multiple applications or multiple instances of the
same application simultaneously on a single screen. This feature is
particularly relevant for large-screen devices like tablets and foldable
phones, enhancing multitasking and user experience.

There are several configurations for multi-window in Android:

Split-screen mode:

This is the most common multi-window implementation, dividing the


screen into two panes where users can place different apps or different
activities within the same app.

Freeform mode:
This allows users to dynamically resize and position multiple app windows
on the screen, offering greater flexibility than split-screen.

Picture-in-picture (PIP):

This mode enables video content to play in a small, resizable window


while the user interacts with other applications.

Activity Embedding:

Introduced in Android 12L (API level 32), activity embedding allows


activity-based applications to display multiple activities simultaneously
within the same application's task window. This is particularly useful for
creating adaptive UIs like list-detail layouts, where a list and its
corresponding detail view can be displayed side-by-side on large screens,
and stacked on small screens. Developers can configure activity
embedding using XML configuration files or through Jetpack
WindowManager API calls.

Varun Shetty B
MCA 2nd Sem, MU

You might also like