0% found this document useful (0 votes)
14 views

Activity Life Cycle

Uploaded by

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

Activity Life Cycle

Uploaded by

Hyma Thottathyl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

1. Draw and explain the lifecycle of an Android Activity class.

Ans:
ACTIVITIES
 An Android activity is one screen of the Android app's user interface.
In that way an Android activity is very similar to windows in a
desktop application.
 An Android app may contain one or more activities, meaning one
or more screens.
 The Android app starts by showing the main activity, and from there
the app may make it possible to open additional activities.
 Unlike programming paradigms in which apps are launched with a
main () method, the Android system initiates code in an activity
instance by invoking specific callback methods that correspond to
specific stages of its lifecycle.

The activity base class defines s series of event that govern the life
cycle of an activity.
i. onCreate () - This is the first callback and called when the
activity is first created.
ii. onStart () - This callback is called when the activity becomes
visible to the user.
iii. onResume () -This is called when the user starts interacting
with the application.
iv. onPause()-The paused activity does not receive user input
and cannot execute any code and called when the current
activity is being paused and the previous activity is being resumed.
v. onStop ()-This callback is called when the activity is no longer
visible.
vi. onDestroy()-This callback is called before the activity is destroyed
by the system.
vii. onRestart()—Called when the activity has been stopped and is
restarting again

The onCreate() and onDestroy() methods are called only once


throughout the activity lifecycle.

Understanding the Life Cycle of an Activity


1. Using Android Studio, create a new Android project and name it
Activity1.
2. In the Activity1 - Activity.java file, add the following highlighted
statements.
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity
{
String tag = "Lifecycle Step";
@Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(tag, "In the onCreate() event");
}
public void onStart()
{
super.onStart();
Log.d(tag, "In the onStart() event");
}
public void onRestart()
{
super.onRestart();
Log.d(tag, "In the onRestart() event");
}
public void onResume()
{
super.onResume();
Log.d(tag, "In the onResume() event");
}
public void onPause()
{
super.onPause();
Log.d(tag, "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d(tag, "In the onStop() event");
}

public void onDestroy()


{
super.onDestroy();
Log.d(tag, "In the onDestroy() event");
}
}
3. Press Shift+F9 to debug the application, or select Run ➪ Debug. Then
select one of your Android Virtual Devices from the pop-up window.
4. When the activity is first loaded, you should see something in logcat
console at the bottom of the Android Studio.
5. If you observe log messages in the LogCat window
again onRestart, onStart and onResume methods are invoked by
system
11-16 06:25:59.396: D/Lifecycle Step(559): In the onCreate()
event 11-16 06:25:59.396: D/Lifecycle Step(559): In the
onStart() event
11-16 06:25:59.396: D/Lifecycle Step(559): In the onResume()
event
6. If you click the Back button on the Android emulator, you see the
following:
11-16 06:29:26.665: D/Lifecycle Step(559): In the onPause()
event
11-16 06:29:28.465: D/Lifecycle Step(559): In the onStop()
event
11-16 06:29:28.465: D/Lifecycle Step(559): In the onDestroy()
event
7. Click the Home button, click the Overview icon, select the Activity101
application, and observe the following:
11-16 06:31:08.905: D/Lifecycle Step(559): In the onCreate()
event 11-16 06:31:08.905: D/Lifecycle Step(559): In the
onStart() event
11-16 06:31:08.925: D/Lifecycle Step(559): In the onResume()
event
8. Click the Home button and then click the Phone button on the
Android emulator so that the activity is pushed to the background.
Observe the output in the logcat window:
11-16 06:32:00.585: D/Lifecycle Step(559): In the onPause()
event
11-16 06:32:05.015: D/Lifecycle Step(559): In the onStop()
event
9. Notice that the onDestroy() event is not called, indicating that the
activity is still in memory. Exit the phone dialer by clicking the Back
button. The activity is now visible again. Observe the output in the
logcat window:
11-16 06:32:50.515: D/Lifecycle(559): In the onRestart() event
11-16 06:32:50.515: D/Lifecycle(559): In the onStart() event
11-16 06:32:50.515: D/Lifecycle(559): In the onResume()
event

The onRestart() event is now fired, followed by the onStart() and


onResume() methods.

2. Explain the procedure to change themes to an activity in an


android application.
Ans:
i. An activity is themed to the default Android theme.
ii. There are two versions of the Material theme available to Android
developers.
iii. Material Light and Material Dark
iv. Either of these themes can be applied from the
AndroidManifest.xml
v. To apply one of the Material themes to an activity, simply modify
the <Application> element in the AndroidManifest.xml file by
changing the default android:theme attribute.

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication" >
<application
android:allowBackup="true“
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name“
android:supportsRtl="true“
android:theme="@style/Theme.MyApplication"
android:theme="@style/Theme.Material3.DayNight“>
<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>
android:theme="@style/Theme.MyApplication"
android: theme="@style/Theme.Material3.DayNight"

android: theme="@style/Theme.Material3.Dark“
3. Explain the steps to hide an activity in an android application, with an
example.

Ans:

Hiding the Activity Title

• To hide the title of an activity if desired (such as when you just


want to display a status update to the user).
• To do so, use the requestWindowFeature() method and pass it
the Window .FEATURE_NO_TITLE constant, like this:
• Now you need to change the theme in the
AndroidManifest.xml to a theme that has no title bar.

package com.example.myapplication;

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

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication" >

<application
android:allowBackup="true“
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name“
android:supportsRtl="true“
android:theme="@android:style/Theme.NoTitleBar”>

4. How to launch activity and sub-activity using intent. Explain it with


suitable example.

Ans:

In Android development, an Activity represents a single screen with a


user interface. To launch an activity from another activity, several key
steps are involved, including setting up intents and handling the
activity lifecycle.

Steps to Launch an Activity

1. Declare the New Activity in AndroidManifest.xml


Every new activity must be registered in the AndroidManifest.xml
file.

2. Create the New Activity Class


Define the logic for the new screen in a Java/Kotlin class that
extends the Activity or AppCompatActivity.

3. Design the Layout for the New Activity (Optional)


Create the UI for the new activity by designing an XML layout file.
4. Use an Intent to Start the New Activity
An Intent helps navigate between activities. You can also pass data
with the intent if needed.

Example of Launching an Activity

1. Declare Activity in AndroidManifest.xml

In AndroidManifest.xml, you need to declare both the activities:

<application ...>

<activity android:name=".MainActivity"/>

<activity android:name=".SecondActivity"/>

</application>

2. Main Activity (Launcher Activity)

This activity contains a button. On clicking the button, it will launch the
SecondActivity.

Java (MainActivity.java):

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

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

btnLaunch.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {


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

// Optional: Add data to the Intent

intent.putExtra("message", "Hello from MainActivity!");

startActivity(intent);

});

3. Second Activity (Target Activity)

The second activity retrieves the message sent from the first activity and
displays it.

Java (SecondActivity.java):

import android.os.Bundle;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_second);

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

// Retrieve data from the Intent

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

textView.setText(message);

}
4. Design the Layouts

activity_main.xml (For MainActivity):

<?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"

android:padding="16dp">

<Button

android:id="@+id/btnLaunch"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Launch Second Activity" />

</RelativeLayout>

activity_second.xml (For SecondActivity):

<?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"

android:padding="16dp">

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Welcome to Second Activity!" />

</RelativeLayout>
Explanation

1. Creating an Intent:
In MainActivity, we create an Intent object to specify the target activity
(Second Activity).

2. Passing Data:
Using intent.putExtra(), we pass a message from MainActivity to
SecondActivity.

3. Retrieving Data:
In SecondActivity, the data is retrieved using
getIntent().getStringExtra().

4. Launching the Activity:


We launch the new activity using startActivity(intent).

Output

1. When the app opens, MainActivity is displayed with a button.

2. On clicking the Launch Second Activity button, SecondActivity opens


and displays the message "Hello from MainActivity!".

This is how you can launch an activity and pass data between activities in
Android.

5. Explain LinearLayout in android with an example.

Ans:

LinearLayout in Android
A LinearLayout is a ViewGroup in Android that arranges its child views
linearly either in a horizontal or vertical direction. This layout
organizes its elements one after the other, either row-wise or column-
wise, depending on the orientation attribute.

Key Attributes of LinearLayout

 orientation: Defines whether child views are arranged


horizontally (horizontal) or vertically (vertical).
 layout_weight: Distributes extra space between child views
proportionally.
 gravity: Aligns all child elements within the layout.
 layout_gravity: Aligns a specific child element within its parent
layout.

Step 1: Define Layout in 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"
android:gravity="center"
android:background="#F5F5F5">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to LinearLayout Example"
android:textSize="18sp"
android:textColor="#333"
android:layout_marginBottom="16dp" />
<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal"

android:gravity="center">

<Button

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="Button 1"

android:layout_marginEnd="8dp" />

<Button

android:layout_width="0dp"

android:layout_height="wrap_content"
android:layout_weight="1"

android:text="Button 2"

android:layout_marginStart="8dp" />

</LinearLayout>

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter some text"

android:layout_marginTop="16dp" />

</LinearLayout>

Explanation of the XML Layout

i. Parent LinearLayout:

o orientation="vertical": Child views are arranged vertically.

o gravity="center": All child views are centered within the


layout.

o padding="16dp": Adds padding around the layout.

ii. TextView:

o A simple text element displayed at the top.

iii. Horizontal LinearLayout:

o Contains two buttons arranged horizontally using


orientation="horizontal".

o layout_weight="1" is used to make the buttons evenly


distribute available space.

iv. EditText:

o Provides a text input field at the bottom.

Output

 The TextView appears at the top, Centered horizontally.


 Two buttons are aligned horizontally in the middle with equal
widths, thanks to layout_weight.

 An EditText appears at the bottom where the user can enter text.

 LinearLayout organizes child views either vertically or


horizontally based on the orientation attribute

 Use layout_weight to distribute space proportionally between child


views.

 Gravity aligns all child views inside the layout, while


layout_gravity aligns a specific child view.

This layout is simple and useful for scenarios where child views need
to be arranged in a single row or column.

6. Explain RelativeLayout in android with an example.

Ans:

RelativeLayout in Android

A RelativeLayout is a ViewGroup that allows you to position its child


views relative to each other or relative to the parent container.
This makes it flexible for creating more complex UIs compared to
LinearLayout, as each child can be positioned based on other elements
(above, below, left, right) or aligned to the parent (centered, aligned to
the start/end, etc.).

Key Attributes of RelativeLayout

 layout_alignParentTop,layout_alignParentBottom,
layout_centerInParent: Align a child relative to the parent
layout.

 layout_below, layout_above, layout_toRightOf,


layout_toLeftOf: Position a child relative to other child views.
 layout_alignStart, layout_alignEnd: Align views relative to the
start or end (used for RTL support).

Example: Using RelativeLayout

 Below is an example where we arrange a TextView, ImageView,


and Button using a RelativeLayout.

Step 1: Define Layout in 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"

android:padding="16dp"

android:background="#F5F5F5">

<TextView

android:id="@+id/headingText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Welcome to RelativeLayout"

android:textSize="20sp"

android:textColor="#333"

android:layout_centerHorizontal="true"

android:layout_marginTop="32dp" />

<ImageView

android:id="@+id/sampleImage"

android:layout_width="150dp"

android:layout_height="150dp"

android:src="@android:drawable/ic_dialog_info"

android:layout_below="@id/headingText"
android:layout_centerHorizontal="true"

android:layout_marginTop="16dp" />

<Button

android:id="@+id/actionButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me"

android:layout_below="@id/sampleImage"

android:layout_centerHorizontal="true"

android:layout_marginTop="24dp" />

</RelativeLayout>

Explanation of the Layout

1. Parent RelativeLayout:

o match_parent width and height make it occupy the entire


screen.

o Padding adds some space inside the layout for better


aesthetics.

2. TextView:

o Positioned at the top and centered horizontally using


layout_centerHorizontal="true".

3. ImageView:

o Positioned below the TextView using


layout_below="@id/headingText".

o Centered horizontally within the layout.

4. Button:
o Positioned below the ImageView using
layout_below="@id/sampleImage".

o Centered horizontally and spaced with


layout_marginTop="24dp".

Output

1. The TextView appears at the top center of the screen.

2. An ImageView is placed below the TextView, centered


horizontally.

3. A Button is aligned below the ImageView, also centered


horizontally.

 RelativeLayout is ideal for more complex UI designs where you need


to align elements relative to each other or to the parent layout.

 Advantages:

 Flexible for creating intricate layouts.

 Reduces nested layouts (unlike LinearLayout which often requires


multiple nested elements).

 Disadvantages:

 May become hard to manage if the layout has too many children.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy