0% found this document useful (0 votes)
19 views24 pages

MAD Unit-1 Chapter-3 by Priyam Jyothi

Chapter 3 covers the use of Activities, Fragments, and Intents in Android development, detailing how to create and manage Activities, their lifecycle, and how to navigate between them using Intents. It explains the importance of UI components, resource management, and applying styles and themes to enhance the user interface. Additionally, it discusses Fragments for modular UI design and the functionality of Intents for communication between components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views24 pages

MAD Unit-1 Chapter-3 by Priyam Jyothi

Chapter 3 covers the use of Activities, Fragments, and Intents in Android development, detailing how to create and manage Activities, their lifecycle, and how to navigate between them using Intents. It explains the importance of UI components, resource management, and applying styles and themes to enhance the user interface. Additionally, it discusses Fragments for modular UI design and the functionality of Intents for communication between components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

CHAPTER 3 - Using Activities, Fragments, and Intents in

Android

Using Activity

Activity in Android is a single, focused thing that a user can do. It provides the window
in which the app draws its UI and is the main entry point for user interaction. Think of it
as the "screen" in traditional applications.

Creating an Activity

Step 1 - Create new java class for activity (ie. Click on New → Empty Activity)

Example - Creating an Activity (MainActivity.java)

package com.example.myfirstapp;

import android.ap p .Activity;


import android.os.Bundle;

public class MainActivity extends Activity {


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

Step 2 - Defining Layout (ie. XML)

Example - Creating an XML Layout (activity_main.xml)

<!-- res/layout/activity_main.xml -->


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android’
android: orientation=”vertical”
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android ;layoLit_height="wrap_content"
android:text="Hello^ World!" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android; layout_height="wrap__content"
android:text="Click Me" />

</LinearLayout>

Step 3 - Declare Activity Manifest

Example - Declaring Manifest File (AndroidManifest.xml)

<!-- AndroidManifest.xml -->


<manifest xmlns:aidroid="http://schemas.android.com/apk/res/android"
package="com. example .myfirst app">
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name">
<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>

Activity Life Cycle

The Activity Lifecycle is a crucial concept in Android development. It describes the


different states an activity goes through during its lifespan. Here are the key stages :

●​ onCreate(): Called when the activity is first created. It's where you should
initialize your activity, such as setting the content view and initializing data
structures.
●​ onStart(): Called when the activity becomes visible to the user. At this point, the
activity is in the "started" state.
●​ onResume(): Called when the activity starts interacting with the user. At this
point, the activity is in the "resumed" state and running in the foreground.
●​ onPause(): Called when the system is about to start resuming another activity.
This is where you should save any changes that should persist beyond the
current user session.
●​ onStop(): Called when the activity is no longer visible to the user. This may
happen because a new activity is starting, an existing one is being resumed, or
the current one is being destroyed.
●​ onDestroy(): Called when the activity is finishing or being destroyed by the
system. This is the final call that the activity will receive.
●​ onRestart(): Called after the activity has been stopped, just prior to it being
started again. Always followed by onStart().

Example - Activity Life Cycle

package com.example.myfirstapp;

import android.ap p .Activity;


import android.os.Bundle;

public class MainActivity extends Activity {


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

@Override
protected void onStart() {
super.onStart();
}

@Override
protected void onResume() {
super.onResume();
}

@Override
protected void onPause() {
super.onPause();
}

@Override
protected void onStop() {
super.onStop();
}

@Override
protected void onDestroy() {
super.onDestroy();
}

@Override
protected void onRestart() {
super.onRestart();
}
}

Features and Functionalities of an Activity

●​ UI Components - Activities host and manage user interface components. These


components include views like buttons, text fields, and images.

●​ Intent Handling - Activities can receive and handle intents, which are messages
from other activities or applications. Intents can start activities, send data, or
request an action.
●​ Lifecycle Management - Activities go through various lifecycle states, allowing
you to manage resources effectively by releasing them when they're not needed
and re-initializing them when necessary.

●​ Fragments - Activities can host fragments, which are modular sections of an


activity. This allows for more flexible UI designs and better handling of different
device configurations.

●​ Navigation - Activities provide a way to navigate between different screens in


an application, using intents or navigation components like the Navigation
Controller.

●​ Resource Management - Activities manage various resources, such as layouts,


strings, images, and themes. These resources are typically stored in XML files in
the res directory.

●​ Data Handling - Activities often handle data passed from other activities or
fragments. They can also retrieve data from databases or web services and
display it to the user.

Applying Styles and Themes to an Activity

Styles - A style in Android is a collection of properties that specify the look and format
for a View or a window. It can be used to share common attributes across multiple
elements to ensure a consistent look and feel throughout the application.

Themes - A theme in Android is a st>'le applies to an entire Activity or application,


rather than an individual View. Themes are used to define the look and feel of all UI
elements within the scope they are applied to. Themes can include styles for various UI
components like buttons, text fields, dialogs, etc.

Example - Applying a Style and Theme to an Activity

colors.xml <resources>
<color name="colorPrimary”>#6200EE</color>
<color name="colorPrimaryDark">#370083</color>
<color name="colorAccent">#03DAC5</color>
</resources>
themes.xml <resources>
<style name="AppTheme"
parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">(S)color/colorPrimaryDark</item>
<item name="colorAc cent">@color/colorAccent</item>
</style>

<!-- Custom Button style -->


<style name="CustomButtonStyle">
<item name="android;layout_width">wrap_content</item>
<item name="android:layout^height">wrap_content</item>
<item name="android:background">@color/colorAccent</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android;padding">10dp</item>
</style>
</resources>

activity_main.xml <?xml version="l.0" encoding="utf-8"?>


<Relative Layout
xmlns:android="http://schemas.android.com/apk/res/android'
xmlns:tools="http;//schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
style="@style/CustomButtonStyle"
android:text="Click Me"
android: layout_centerInParent=" true"/>

</RelativeLayout>

AndroidManifest.xml <manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package=”com.example.myfirstapp">
<application
android:allowBackup="true"
android;icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon=”@ipmap/ic_launcher_round”
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>

MainActivity.java package com. Example.myfirstapp;

import android.05.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


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

Hiding the Activity Title

Hiding the title of an activity is a straightforward task in Android. You can achieve this
by modifying the activity's theme in your AndroidManifest.xml file or by using Java
code within your activity.

Example - Hiding Activity Title

AndroidManifest.xml

<activity android:name=".MainActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>

OR

Styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
<style name="NoActionBarTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
</resources>

Using Intents

An Intent in Android is an abstract description of an operation to be performed. It can


be used for various purposes like :

●​ Starting a new activity.


●​ Starting a service.
●​ Delivering a broadcast.

Features and Functionalities of Intents

●​ Starting Activities: Intents can be used to start an activity or a set of activities.


●​ Starting Services: Intents are used to start or bind a service.
●​ Broadcasting: Intents can be used to send a broadcast message, such as
system events (e.g., battery low, network changes).
●​ Communication Between Components: Intents allow different parts of the
application (or even different apps) to communicate by sending data.

Creating an Intent

Syntax -

Intent intent = new Intent(CurrentActivity .this, TargetActivity.class);


Intent: This is a class in the Android framework used to define an action to be
performed, such as starting another activity.

CurrentActivity.this: This parameter specifies the current context, usually the activity
from which the intent is being created. It provides the necessary context for the intent
to start the new activity.

TargetActivityclass: This parameter specifies the class of the activity that you want to
navigate to. It tells the Android system which activity to launch.

Navigating Between Activities (or) Linking Activities Using Intents

One of the most common uses of Intents is navigating between activities. Here's how
you can link activities and pass data between them:

Starting a New Activity:

To start a new activity, you can use an explicit Intent. ( ie. MainActivity →
SecondActivity )

MainActivity.java -

Intent intent = new Intent(MainActivity.this, SecondActivity.class);


startActivity(intent);

Passing Data Between Activities:

You can attach data to the Intent using the putExtra() method.

MainActivity.java -

Intent intent = new Intent(MainActivity.this, SecondActivity.class);


intent.putExtra("message", "Hello, Second Activity!");
startActivity(intent);

SecondActivity.java -

String message = getIntent().getStringExtra("message");


TextView textView = findViewById(R.id.textView);
textView.setText(message);

Returning Data from Activity:

You can also return data from one activity to another using setResult() and
onActivityResult().

SecondActivity.java [ Sending the Results ] -

Intent resultIntent = new Intent();


resultIntent.putExtra("result", "Data from Second Activity");
setResult(RESULT_OK, resultIntent);
finish();

MainActivity.java [ Receiving the Results ] -

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
textView.setText(result);
}
}

Types of Intents

Explicit Intent - An explicit Intent directly specifies the target activity by class name.
Used when you specify the exact class to invoke. It works well when you know exactly
which component you want to launch.

Example -

Intent intent = new Intent(MainActivity.this, SecondActivity.class);


startActivity(intent);
Implicit Intent - Used when you don’t specify a particular class but want to invoke a
component that can handle the action.

Example -

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));


startActivity(intent);

Intent Class Methods

Method Description Example

Intent() Constructor to create a new Intent intent = new Intent();


empty Intent.

setAction(String Sets a specified action for intent.setAction[Intent.ACTION_VIEW);


action) the Intent.

getAction() Retrieves the action String action = intent.getAction();


associated with the Intent.

setData(Uri data) Sets the data URl for the intent.setData(Uri.parse("https://www.google.


Intent. com"));

getData() Retrieves the data URI Uri data = intent.getData();


associated with the Intent.

setType(String type) Sets an explicit MIME data intent.setType("image/*");


type for the Intent.

getType() Retrieves the MIME type set String type = intent.getType();


for the Intent.

toString() Returns a string String intentString = intent.toString();


representation of the Intent.

Intent Class Attributes

These are some of the key attributes used in an Intent :


●​ Action: The action to be performed (e.g., Intent.ACTION_VIEW,
Intent.ACTION_SEND).
●​ Data: The URI associated with the intent (e.g., a webpage URL or file URI).
●​ Category: Defines the category of the activity being invoked (e.g.,
Intent.CATEGORY_DEFAULT).
●​ Extras: A bundle of data that can be attached to an Intent. This allows passing
additional data (e.g., user input, preferences).
●​ Flags: Flags that control how the activity is launched, such as
Intent.FLAG_ACTIVITY_NEW_TASK.

Intent Filters

An Intent Filter is a component in an android manifest that declares which intents a


component (activity, service, or broadcast receiver) can handle. By using intent filters,
components can specify which types of intents they are interested in.

Example - ( Declaring Intent Filter for Activity )

<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="com.example.ACTION_VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>

Using the Intent Object to Invoke Built-in Application

Example Launching the Contact App

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android”
android:layout_width="match_parent"
android:layout_height=”match_parent">
<Button
android;id="@+id/button_openContacts"
android:layout_width="wrap_content"
android:layout_height="wrap__content"
android:text=“Open Contacts"
android : layout__centerInParent="true" />

</RelativeLayout>

MainActivity.java package com.example.contactslauncher;

import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


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

Button btnContact = findViewByld(R.id.button_openContacts)


btnContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACT10N_VIEW);
intent.setData(ContactsContract.Contacts. CONTENT_URI) ;
startActivity(intent);
}
} );
}
}
Output

Fragments

A Fragment represents a portion of user interface or behavior in an Activity. It is used


to build dynamic and flexible UIs, especially on large screens such as tablets and
smartphones.

Features and Benefits of Fragments

FEATURES -

●​ Modularization: Fragments allow for code modularity. Each fragment can

represent a specific feature or UI component.


●​ Reusability: Fragments can be reused across multiple activities or

configurations.

●​ Dynamic UI: You can dynamically add, remove, or replace fragments during

runtime.

●​ Compatibility: Fragments allow for optimized layouts across different screen

sizes, providing a better user experience.

●​ Lifecycle: Fragments have their own lifecycle, which is tied to the activity's

lifecycle, making them adaptable for various app behaviors.

BENEFITS -

●​ Flexible UI Design: Fragments make it easy to create responsive layouts for

devices with different screen sizes. For example, on larger devices like tablets,

you can show multiple fragments side by side.

●​ Separation of Concerns: By breaking an app's UI into fragments, you can

ensure each fragment handles specific functionality, improving the structure and

maintainability.

●​ Reusability: Fragments are reusable across different activities, saving

development time and effort.

Fragment Lifecycle

The lifecycle of a fragment is quite similar to that of an activity, but with additional
states and methods to manage its specific context and interactions with the hosting
activity.
Here's an overview of the key stages:

●​ onAttach(): Called when the fragment has been associated with the activity. You
can get a reference to the activity in this method.
●​ onCreate(): Called to do initial creation of the fragment.
●​ onStart(): Called when the fragment becomes visible.
●​ onResume(): Called when the fragment is interacting with the user.
●​ onPause(): Called when the fragment is no longer interacting with the user but is
still visible.
●​ onStop(): Called when the fragment is no longer visible.
●​ onDestroyView(): Called when the fragment's view is about to be destroyed.
●​ onDestroy(): Called when the fragment is about to be destroyed.
●​ onDetach(): Called when the fragment is detached from the activity.
●​ onCreateView(): Called to create the fragment's view. This is where you inflate
the layout for the fragment.

Example - Fragment Lifecycle

public class ItemListFragment extends Fragment {

@Override
public void onAttach(Context context) {
super.onAttach(context);
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment_item_list, container, false);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}

@Override
public void onStart() {
super.onStart();
}

@Override
public void onResume() {
super.onResume();
}

@Override
public void onPause() {
super.onPause();
}

@Override
public void onStop() {
super.onStop();
}

@Override
public void onDestroyView() {
super.onDestroyView();
}

@Override
public void onDestroy() {
super.onDestroy();
}

@Override
public void onDetach() {
super.onDetach();
}
}

Implementing, Creating and Using Fragments

Creating fragments in Android involves creating modular components for your app’s UI
that can be reused across multiple activities. A fragment represents a portion of the
user interface (UI) of an activity, and it has its own lifecycle that can be controlled
independently of the parent activity.

Step 1 : Define a Fragment Class


A fragment in Android is defined as a class that extends Fragment. This class will
override the onCreateView() method to define the fragment's layout.

Creating Fragment class [ Fragment.java ] -

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;

public class ExampleFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.fragment_example, container, false);
}
}

Creating Fragment Layout [ fragment_layout.xml ] -


<?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"
android:padding="16dp">

<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello from Fragment!"
android:textSize="18sp"/>

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

</LinearLayout>

Step 2 : Add the Fragment to an Activity


You can add the fragment to an activity either statically (by declaring it in XML) or
dynamically (by using a FragmentTransaction in the activity code).

Creating Activity XML [ activity_main.xml ] -

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


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- Add the fragment statically -->


<fragment
android:id="@+id/example_fragment"
android:name="com.example.app.ExampleFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>

Creating Activity Class [ MainActivity.java ] -

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

OR

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

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

ExampleFragment exampleFragment = new ExampleFragment();

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();


transaction.replace(R.id.fragment_container, exampleFragment);
transaction.commit();
}
}

Step 3 : Handling Fragment Interaction


Fragments often need to communicate with the parent activity or other fragments. One
common way to handle this is by defining an interface in the fragment and
implementing that interface in the parent activity.

Defining an Interface in Fragment [ Fragment.java ] -

public class ExampleFragment extends Fragment {

private OnButtonClickListener mListener;

public interface OnButtonClickListener {


void onButtonClick(String message);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_example, container, false);

Button button = rootView.findViewById(R.id.button);


button.setOnClickListener(v -> {
if (mListener != null) {
mListener.onButtonClick("Hello from Fragment!");
}
});

return rootView;
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnButtonClickListener) {
mListener = (OnButtonClickListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement
OnButtonClickListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}

Implementing Interface in Parent Activity [ MainActivity.java ] -

import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements


ExampleFragment.OnButtonClickListener {

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

if (savedInstanceState == null) {
ExampleFragment fragment = new ExampleFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}
}

@Override
public void onButtonClick(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}

Step 4 : Managing the Fragment Lifecycle


●​ onAttach(): Called when the fragment is attached to the activity.
●​ onCreate(): Called when the fragment is being created.
●​ onCreateView(): Called to inflate the fragment's layout.
●​ onActivityCreated(): Called when the activity's onCreate() method is finished.
●​ onStart(), onResume(): Fragment becomes visible to the user.
●​ onPause(), onStop(): Fragment is no longer visible.
●​ onDestroyView(): The fragment's view is being destroyed.
●​ onDetach(): The fragment is detached from the activity.

Adding Fragments Dynamically

Dynamically adding fragments is crucial for creating flexible, responsive apps that can
adapt to different screen sizes. You can add, remove, and replace fragments at runtime
based on user interactions or device configurations.

Creating Fragments -

MyFragment fragment = new MyFragment();

Starting Transactions -

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();


Adding Fragments -

transaction.add(R.id.fragment_container, fragment);

Committing Transactions -

transaction.commit();

Example - Adding Fragment Dynamically

if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}

MyFragment fragment = new MyFragment();

getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container,
fragment)..commit();
}

You might also like