Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Mobile Application Development: by Wahid Qayyum

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 271

Mobile Application

Development
by Wahid Qayyum
The Course
• Title
Mobile Application Development

• Code
SE326

• Prerequisites
Object Oriented Programming (CSC321)

• Instructor
Wahid Qayyum

• Email
wahidqayyum@lgu.edu.pk
What you will learn in this course
• Understand fundamentals of Android Development.
• Anatomy of an Android Application.
• Understand complete Lifecycle of an Android Application.
• How to build GUI of an Android Application.
• All types of mobile application’s Layouts.
• Backend Programming of an Android Application.
• Creating project on Android Studio.
• How to create APK and deploy it.
Mobile Computing Family

Mobile Computing is a technology which allows a wireless enabled electronic device to:

 Compute a computational problem

 Data, voice and video reception, transmission and processing anywhere and anytime.
Main Concepts

 Mobile Communication

 Mobile Hardware

 Mobile Software
Mobile Communication

 An infrastructure made to provide data, voice and video communication


over unguided/unbounded media.

 The media is electromagnetic waves which require no medium to travel and


propagate by their own electric and magnetic field. 
 Bluetooth
 Wi-Fi Network
 Cellular Network
Mobile Hardware

 Collection of electronic components.

 Used in computation (Processor, Memory), physical


interaction with user (IOs) and communication (printed
wirings, sensors, wireless technologies).
Mobile Hardware
 Processor
Mobile CPU, smaller in size, low energy consumption, sleep modes, single to multi core.
 GPU
Graphic processing unit, dedicated processor, processes and renders HD graphics, animations and videos
smoothly.
 ISP
Image Signal Processor, dedicated processor, enhance camera functions, image and video capturing, high-
resolution support etc.
 VPU
Video Processing Unit, dedicated processor, video encoding and decoding
Mobile Hardware
 RPU
Radio Processing Unit, contains Bluetooth, WIFI, Radio, 3G/4G Modem, transmits, receives and process
radio signals and digital data.

 ROM
Write-Protected flash contains very first code run by the processor

 Memory
RAM, low power, double data rate, dynamic RAM.

 Storage
Internal Storage, two partitions, one for firmware and other for user apps, files and data.
External Storage, microSD Card.
Mobile Hardware
 Display
 Primary camera W/WO flash.
 Secondary camera W/WO flash.
 Battery.
 Speakers.
 Microphones.
 And other components…
Mobile Software

• An operating system which interact with mobile hardware and


user programs to perform computation and manage hardware
and software resources. It also deals with the services of
mobility (connectivity, communication, mobility).
Mobile Software | iOS
 Developed by Apple Inc.

 Initial Release: 2007

 Current Status: Present

 Written In: C, C++, Objective-C, Swift

 OS Family: Unix based

 Source Model: Closed


Mobile Software | Android
 Developed by Google

 Initial Release: 2008

 Current Status: Present

 Written In: JAVA

 OS Family: Linux based

 Source Model: Open


Mobile Software | Windows
 Developed by Microsoft

 Initial Release: 2010

 Current Status: Present

 Written In: C, C++

 OS Family: Microsoft Windows

 Source model: Closed


Evolution of Mobile Phones
Traditional Phones

• Pick up the Phone

• Start Talking

• When finished talking, Hang Up!


Traditional Mobile Phones

• Pick up the Phone

• Start Talking

• When finished talking, Hang Up!

• Send and Receive Messages

• A few games
Featured Mobile Phones

• Calls, SMS, Games

• Camera

• Use Internet on Mobile Phone

• Check Emails
Smart Phones
• Calls, SMS, Games
• Camera
• Use Internet on Mobile Phone
• Check Emails
• Enjoy Music
• Watch Videos
• Use Social Networks
• Maps
• Read Books
• Do almost everything that can be done on a Computer .
Why to develop for Mobile?
• World’s Population
• Is Around
• 7.7 Billion
Why Android Development
What is Android?

Android is an open source and Linux-based Operating System for mobile devices such as


smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by
Google.
The first beta version of the Android Software Development Kit (SDK) was released by Google
in 2007 where as the first commercial version, Android 1.0, was released in September 2008.
Why Android?
Open Source

Larger Developer and


community reach

Increased Marketing

Inter app integration

Reduced cost of
Develoment

Higher Success Ratio

Rich Development
Environment
Features of Android
• Beautiful UI
• Connectivity
• Storage
• Media Support
• Messaging
• Web Browser
• Multi-touch
• Multi-tasking
• Resizeable Widgets
• Multi Language
• Wi-Fi Direct
Categories of Android Application
Music Sports Travel

Food & Drink Weather Navigation

Multimedia Finance News

Social Media Business Education

Utilities Healthcare Games


History of Android
Alpha 1.0Beta 1.1 Cupcake 1.5

Donut 1.6Eclair 2.0 Froyo 2.2

Gingerbread 2.3 Honeycomb 3.0 Ice CreamSanwich 4.0

Jelly Bean 4.1 KitKat 4.4 Lollipop 5.0

Marshmallow 6.0 Nougat 7.0 Oreo 8.0

Pie 9.0 Android 10.0


Android Architecture

Android operating system is a stack of


software components which is roughly
divided into five sections an d four main
layers.
Linux Kernel
• At the bottom of the layers is Linux. This provides a level of abstraction between the
device hardware and it contains all the essential hardware drivers like camera, keypad,
display etc.
• The kernel handles all the things that Linux is really good at such as networking and a
vast array of device drivers, which take the pain out of interfacing to peripheral hardware.
Libraries
• On top of Linux kernel there is a set of libraries including open-source Web browser
engine WebKit, well known library libc.
• SQLite database which is a useful repository for storage and sharing of application data,
libraries to play and record audio and video, SSL libraries responsible for Internet
security etc.
Libraries
• android.app
• android.content
• android.database
• android.opengl
• android.os
• android.text
• android.view
• android.widget
• android.webkit
Android Runtime
• This is the third section of the architecture and available on the second layer from the
bottom. This section provides a key component called Dalvik Virtual Machine(DVM)
which is a kind of Java Virtual Machine specially designed and optimized for Android.
• The DVM makes use of Linux core features like memory management and multi-
threading, which is intrinsic in the Java language. The Dalvik VM enables every Android
application to run in its own process, with its own instance of the Dalvik virtual machine.
• The Android runtime also provides a set of core libraries which enable Android
application developers to write Android applications using standard Java programming
language.
Application Framework
The Application Framework layer provides many higher-level services to applications in the
form of Java classes. Application developers are allowed to make use of these services in
their applications.
• Activity Manager

• Content Providers

• Resource Manager

• Notifications Manager 

• View System
Applications
This is the top layer. You will write your application to be installed on this layer only.
Examples of such applications are Contacts Books, Browser, Games etc.
Anatomy of an Android Application
• Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.
• There are following four main components that can be used within an Android application:
• Activities
• Services
• Broadcast Receivers
• Content Providers
Activities
• They dictate the UI and handle the user interaction to the smart phone screen.
• An activity is implemented as a subclass of Activity class as follows
• public class MainActivity extends Activity
{
}
Services
• They handle background processing associated with an application.
• A service is implemented as a subclass of Service class as follows
• public class MyService extends Service
{
}
Broadcast Receivers
• They handle communication between Android OS and applications.
• A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcasted as an Intent object.
• public class MyReceiver extends BroadcastReceiver

public void onReceive (context, intent) {

}
Content Providers
• They handle data and database management issues.
• A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.
• public class MyContentProvider extends ContentProvider

public void onCreate() {
}
}
Additional Components
• Fragment Represents a portion of user interface in an Activity.
• View UI elements that are drawn on-screen including buttons, lists forms etc.
• Layout View hierarchies that control screen format and appearance of the views.
• Intent Messages wiring components together.
• Resource External elements, such as strings, constants and drawable pictures.
• Manifest Configuration file for the application.
Android Developer Fundamentals V2

Build your first


app
Lesson 1

This work is licensed under a


Your first
Android Developer Fundamentals V2 Android app
Creative Commons Attribution 4.0 Inter
national License 4040
1.1 Your first Android app

41
Contents

● Android Studio
● Creating "Hello World" app in Android Studio
● Basic app development workflow with Android Studio
● Running apps on virtual and physical devices

42
Prerequisites

● Java Programming Language


● Object-oriented programming
● XML - properties / attributes
● Using an IDE for development and debugging

43
Android Studio

44
What is Android Studio?

● Android integrated development environment (IDE)


● Project and Activity templates
● Layout editor
● Testing tools
● Gradle-based build
● Log console and debugger
● Emulators

45
Android Studio interface

1. Toolbar
2. Navigation bar
3. Project pane
4. Editor
5. Tabs for other
panes

46
Installation Overview

● Mac, Windows, or Linux


● Download and install Android Studio from https://developer.android.com/studio/
● See 1.1 P: Android Studio and Hello World

47
Creating your
first Android app

48
Start Android Studio

49
Create a project inside Android Studio

50
Name your app

51
Pick activity template

Choose templates for


common activities,
such as maps or
navigation drawers.

Pick Empty Activity or


Basic Activity for
simple and custom
activities.
52
Name your activity

● Good practice:
○ Name main activity
MainActivity
○ Name layout
activity_main
● Use AppCompat
● Generating layout file
is convenient

53
Project folders

1. manifests—Android Manifest file -


description of app read by the Android
runtime
2. java—Java source code packages
3. res—Resources (XML) - layout,
strings, images, dimensions, colors...
4. build.gradle—Gradle build files

54
Gradle build system

● Modern build subsystem in Android Studio


● Three build.gradle:

○ project
○ module
○ settings

● Typically not necessary to know low-level Gradle details


● Learn more about gradle at https://gradle.org/

55
Run your app

1. Run

2. Select virtual
or physical
device
3. OK
56 56
Create a virtual device

Use emulators to test app on different versions of Android and form factors.

Tools > Android > AVD Manager or:

57
Configure virtual device

1. Choose hardware
2. Select Android version
3. Finalize

58
Run on a virtual device

59
Run on a physical device

1. Turn on Developer Options:


a. Settings > About phone
b. Tap Build number seven times
2. Turn on USB Debugging
a. Settings > Developer Options > USB Debugging
3. Connect phone to computer with cable

Windows/Linux additional setup:


● Using Hardware Devices

Windows drivers:
● OEM USB Drivers

60
Get feedback as your app runs

1. Emulator running the


app
2. Run pane
3. Run tab to open or close
the Run pane

61
Adding logging to your app

● As the app runs, the Logcat pane shows information


● Add logging statements to your app that will show up in the Logcat pane
● Set filters in Logcat pane to see what's important to you
● Search using tags

62
The Logcat pane

1. Logcat tab to show


Logcat pane

2. Log level menu

63
Logging statement

import android.util.Log;

// Use class name as tag


private static final String TAG =
MainActivity.class.getSimpleName();

// Show message in Android Monitor, logcat pane


// Log.<log-level>(TAG, "Message");
Log.d(TAG, “Creating the URI…”);

64
Learn more

● Meet Android Studio


● Official Android documentation at developer.android.com
● Create and Manage Virtual Devices
● Supporting Different Platform Versions
● Supporting Multiple Screens

65
Learn even more

● Gradle Wikipedia page


● Google Java Programming Language style guide
● Find answers at Stackoverflow.com

66
What's Next?

● Concept Chapter: 1.1 Your first Android app


● Practical: 1.1 Android Studio and Hello World

67
END

68
Android Developer Fundamentals V2

Build your first


app

Lesson 1

This work is licensed under a


Your first
Android Developer Fundamentals V2 Android app
Creative Commons Attribution 4.0 Inter
national License 6969
1.2 Layouts and resources for
the UI

70
Contents

● Views, view groups, and view hierarchy


● The layout editor and ConstraintLayout
● Event handling
● Resources and measurements

71
Views

72
Everything you see is a view

If you look at your mobile device,


every user interface element that you see is a View.

Views

73
What is a view?

View subclasses are basic user interface building blocks


● Display text (TextView class), edit text (EditText class)
● Buttons (Button class), menus, other controls
● Scrollable (ScrollView, RecyclerView)
● Show images (ImageView)
● Group views (ConstraintLayout and LinearLayout)

74
Examples of view subclasses

Button CheckBox

EditText RadioButton

Slider Switch

75
View attributes

● Color, dimensions, positioning


● May have focus (e.g., selected to receive user input)
● May be interactive (respond to user clicks)
● May be visible or not
● Relationships to other views

76
Create views and layouts

● Android Studio layout editor: visual representation of XML


● XML editor
● Java code

77
Android Studio layout editor

1. XML layout file


2. Design and Text tabs
3. Palette pane
4. Component Tree
5. Design and blueprint
panes
6. Attributes tab

78
View defined in XML

<TextView
android:id="@+id/show_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/myBackgroundColor"
android:text="@string/count_initial_value"
android:textColor="@color/colorPrimary"
android:textSize="@dimen/count_text_size"
android:textStyle="bold"
/>
79
View attributes in XML

android:<property_name>="<property_value>"
Example: android:layout_width="match_parent"

android:<property_name>="@<resource_type>/resource_id"
Example: android:text="@string/button_label_next"

android:<property_name>="@+id/view_id"
Example: android:id="@+id/show_count"

80
Create View in Java code

context
In an Activity:

TextView myText = new TextView(this);

myText.setText("Display this text!");

81
What is the context?

● Context is an interface to global information about an application environment


● Get the context:
Context context = getApplicationContext();
● An Activity is its own context:
TextView myText = new TextView(this);

82
Custom views

● Over 100 (!) different types of views available from the Android system, all children of the View class
● If necessary, create custom views by subclassing existing views or the View class

83
ViewGroup and
View hierarchy

84
ViewGroup contains "child" views

● ConstraintLayout: Positions UI elements using constraint connections to other elements and to the
layout edges
● ScrollView: Contains one element and enables scrolling
● RecyclerView: Contains a list of elements and enables scrolling by adding and removing elements
dynamically

85
ViewGroups for layouts

Layouts
● are specific types of ViewGroups (subclasses of ViewGroup)
● contain child views
● can be in a row, column, grid, table, absolute

86
Common Layout Classes

LinearLayout ConstraintLayout GridLayout TableLayout

87
Common Layout Classes

● ConstraintLayout: Connect views with constraints


● LinearLayout: Horizontal or vertical row
● RelativeLayout: Child views relative to each other
● TableLayout: Rows and columns
● FrameLayout: Shows one child of a stack of children

88
Class hierarchy vs. layout hierarchy

● View class-hierarchy is standard object-oriented class inheritance


○ For example, Button is-a TextView is-a View is-an Object
○ Superclass-subclass relationship

● Layout hierarchy is how views are visually arranged


○ For example, LinearLayout can contain Buttons arranged in a row
○ Parent-child relationship

89
Hierarchy of viewgroups and views

ViewGroup Root view is always a ViewGroup

ViewGroup View View

View View View

90
View hierarchy and screen layout

91
View hierarchy in the layout editor

92
Layout created in XML

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
... />
<TextView
... />
<Button
... />
</LinearLayout

93
Layout created in Java Activity code

LinearLayout linearL = new LinearLayout(this);


linearL.setOrientation(LinearLayout.VERTICAL);

TextView myText = new TextView(this);


myText.setText("Display this text!");

linearL.addView(myText);
setContentView(linearL);

94
Set width and height in Java code

Set the width and height of a view:

LinearLayout.LayoutParams layoutParams =
new Linear.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_CONTENT);

myView.setLayoutParams(layoutParams);

95
Best practices for view hierarchies

● Arrangement of view hierarchy affects app performance


● Use smallest number of simplest views possible
● Keep the hierarchy flat—limit nesting of views and view
groups

96
The layout editor
and Constraint
Layout

97
The layout editor with ConstraintLayout

● Connect UI elements to parent layout


● Resize and position elements
● Align elements to others
● Adjust margins and dimensions
● Change attributes

98
What is ConstraintLayout?

● Default layout for new Android Studio project


● ViewGroup that offers flexibility for layout design
● Provides constraints to determine positions and alignment of UI elements
● Constraint is a connection to another view, parent layout, or invisible guideline

99
Layout editor main toolbar

1. Select Design Surface: Design and Blueprint panes


2. Orientation in Editor: Portrait and Landscape
3. Device in Editor: Choose device for preview
4. API Version in Editor: Choose API for preview
5. Theme in Editor: Choose theme for preview
6. Locale in Editor: Choose language/locale for preview

10
ConstraintLayout toolbar in layout editor

1. Show: Show Constraints and Show Margins


2. Autoconnect: Enable or disable
3. Clear All Constraints: Clear all constraints in layout
4. Infer Constraints: Create constraints by inference
5. Default Margins: Set default margins
6. Pack: Pack or expand selected elements
7. Align: Align selected elements
8. Guidelines: Add vertical or horizontal guidelines
9. Zoom controls: Zoom in or out

10
Autoconnect

● Enable Autoconnect in toolbar if disabled


● Drag element to any part of a layout
● Autoconnect generates constraints against
parent layout

10
ConstraintLayout handles

1. Resizing handle
2. Constraint line and handle
3. Constraint handle
4. Baseline handle

10
Align elements by baseline

1. Click the baseline


constraint button
2. Drag from baseline to
other element's baseline

10
Attributes pane

● Click the Attributes tab


● Attributes pane includes:
○ Margin controls for
positioning
○ Attributes such as
layout_width

10
Attributes pane view inspector

1. Vertical view size control specifies


layout_height
2. Horizontal view size control
specifies layout_width
3. Attributes pane close button

10
Layout_width and layout_height

layout_width and layout_height change with size controls


● match_constraint: Expands element to fill its parent
● wrap_content: Shrinks element to enclose content
● Fixed number of dp (density-independent pixels)

10
Set attributes

To view and edit all attributes for element:

1. Click Attributes tab

2. Select element in design, blueprint, or Component Tree

3. Change most-used attributes

4. Click at top or View more attributes at bottom to see and change more attributes

10
Set attributes example: TextView

10
Preview layouts

Preview layout with horizontal/vertical orientation:

1. Click Orientation in Editor button


2. Choose Switch to Landscape or Switch to Portrait

Preview layout with different devices:

3. Click Device in Editor button


4. Choose device

11
Create layout variant for landscape

1. Click Orientation in Editor button

2. Choose Create Landscape Variation

3. Layout variant created: activity_main.xml (land)

4. Edit the layout variant as needed

11
Create layout variant for tablet

1. Click Orientation in Layout Editor

2. Choose Create layout x-large Variation

3. Layout variant created: activity_main.xml (xlarge)

4. Edit the layout variant as needed

11
Event Handling

11
Events

Something that happens


● In UI: Click, tap, drag
● Device: DetectedActivity such as walking, driving, tilting
● Events are "noticed" by the Android system

11
Event Handlers

Methods that do something in response to a click


● A method, called an event handler, is triggered by a specific event and does something in response to
the event

11
Attach in XML and implement in Java

Attach handler to view in XML layout: Implement handler in Java activity:

android:onClick="showToast" public void showToast(View view) {


String msg = "Hello Toast!";
Toast toast = Toast.makeText(
this, msg, duration);
toast.show();
}
}

11
Alternative: Set click handler in Java

final Button button = (Button) findViewById(R.id.button_id);


button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String msg = "Hello Toast!";
Toast toast = Toast.makeText(this, msg, duration);
toast.show();
}
});

11
Resources and
measurements

11
Resources

● Separate static data from code in your layouts.


● Strings, dimensions, images, menu text, colors, styles
● Useful for localization

11
Where are the resources in your project?

resources and resource files


stored in res folder

12
Refer to resources in code

● Layout:
R.layout.activity_main
setContentView(R.layout.activity_main);
● View:
R.id.recyclerview
rv = (RecyclerView) findViewById(R.id.recyclerview);
● String:
In Java: R.string.title
In XML: android:text="@string/title"

12
Measurements

● Density-independent Pixels (dp): for Views


● Scale-independent Pixels (sp): for text

Don't use device-dependent or density-dependent units:


● Actual Pixels (px)
● Actual Measurement (in, mm)
● Points - typography 1/72 inch (pt)

12
Learn more

12
Learn more

Views:
● View class documentation
● device independent pixels
● Button class documentation
● TextView class documentation
Layouts:
● developer.android.com Layouts
● Common Layout Objects

12
Learn even more

Resources: Other:
● Android resources ● Android Studio documentation
● Color class definition ● Image Asset Studio
● R.color resources ● UI Overview
● Supporting Different Densities ● Vocabulary words and concepts glos
● Color Hex Color Codes sary
● Model-View-Presenter
(MVP) architecture pattern
● Architectural patterns

12
What's Next?

● Concept Chapter: 1.2 Layouts and resources for the UI


● Practicals:
○ 1.2A : Your first interactive UI
○ 1.2B : The layout editor

12
END

12
Android Developer Fundamentals V2

Activities and
Intents

Lesson 2

This work is licensed under a


Your first
Android Developer Fundamentals V2 Android app
Creative Commons Attribution 4.0 Inter
national License 12128
2.1 Activities and Intents

12
Contents

● Activities
● Defining an Activity
● Starting a new Activity with an Intent
● Passing data between activities with extras
● Navigating between activities

13
Activities
(high-level view)

13
What is an Activity?

● An Activity is an application component


● Represents one window, one hierarchy of views
● Typically fills the screen, but can be embedded in other Activity or a appear as floating window
● Java class, typically one Activity in one file

13
What does an Activity do?

● Represents an activity, such as ordering groceries, sending email, or getting directions


● Handles user interactions, such as button clicks, text entry, or login verification
● Can start other activities in the same or other apps
● Has a life cycle—is created, started, runs, is paused, resumed, stopped, and destroyed

13
Examples of activities

13
Apps and activities

● Activities are loosely tied together to make up an app


● First Activity user sees is typically called "main activity"
● Activities can be organized in parent-child relationships in the Android manifest to aid navigation

13
Layouts and Activities

● An Activity typically has a UI layout


● Layout is usually defined in one or more XML files
● Activity "inflates" layout as part of being created

13
Implementing
Activities

13
Implement new activities

1. Define layout in XML

2. Define Activity Java class

○ extends AppCompatActivity
3. Connect Activity with Layout

○ Set content view in onCreate()


4. Declare Activity in the Android manifest

13
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Let's Shop for Food!" />
</RelativeLayout>

13
2. Define Activity Java class

public class MainActivity extends AppCompatActivity {


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

14
3. Connect activity with layout

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Resource is layout in this XML file

14
4. Declare activity in Android manifest

<activity android:name=".MainActivity">

14
4. Declare main activity in manifest

MainActivity needs to include intent-filter to start from launcher

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

14
Intents

14
What is an intent?

An Intent is a description of an operation to be performed.

An Intent is an object used to request an action from another app component via the Android system.

Originator App component

Intent Action
Android
System

14
What can intents do?
● Start an Activity

○ A button click starts a new Activity for text entry


○ Clicking Share opens an app that allows you to post a photo
● Start an Service

○ Initiate downloading a file in the background


● Deliver Broadcast

○ The system informs everybody that the phone is now charging

14
Explicit and implicit intents
Explicit Intent
● Starts a specific Activity
○ Request tea with milk delivered by Nikita
○ Main activity starts the ViewShoppingCart Activity
Implicit Intent
● Asks system to find an Activity that can handle this request
○ Find an open store that sells green tea
○ Clicking Share opens a chooser with a list of apps

14
Starting
Activities

14
Start an Activity with an explicit intent

To start a specific Activity, use an explicit Intent

1. Create an Intent

○ Intent intent = new Intent(this, ActivityName.class);


2. Use the Intent to start the Activity

○ startActivity(intent);

14
Start an Activity with implicit intent

To ask Android to find an Activity to handle your request, use an implicit Intent

1. Create an Intent

○ Intent intent = new Intent(action, uri);


2. Use the Intent to start the Activity

○ startActivity(intent);

15
Implicit Intents - Examples

Show a web page


Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = Uri.parse("tel:8005551234");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
15
How Activities Run

● All Activity instances are managed by the Android runtime


● Started by an "Intent", a message to the Android runtime to run an
activity

User clicks MainActivity FoodListActivity OrderActivity


launcher icon What do you want to do? Choose food items...Next Place order

Intent: Start Start Intent: Start choose Intent: Start finish


app Android Android food order Android order activity
System
main Shop System System
activity activity

15
Sending and
Receiving Data

15
Two types of sending data with intents

● Data—one piece of information whose data location can be represented by an URI

● Extras—one or more pieces of information as a collection of key-value pairs in a Bundle

15
Sending and retrieving data

In the first (sending) Activity:


1. Create the Intent object
2. Put data or extras into that Intent
3. Start the new Activity with startActivity()

In the second (receiving) Activity:


4. Get the Intent object, the Activity was started with
5. Retrieve the data or extras from the Intent object

15
Putting a URI as intent data

// A web page URL


intent.setData(
Uri.parse("http://www.google.com"));

// a Sample file URI


intent.setData(
Uri.fromFile(new File("/sdcard/sample.jpg")));

15
Put information into intent extras

● putExtra(String name, int value)


⇒ intent.putExtra("level", 406);
● putExtra(String name, String[] value)
⇒ String[] foodList = {"Rice", "Beans", "Fruit"};
intent.putExtra("food", foodList);
● putExtras(bundle);
⇒ if lots of data, first create a bundle and pass the bundle.
● See documentation for all
15
Sending data to an activity with extras

public static final String EXTRA_MESSAGE_KEY =


"com.example.android.twoactivities.extra.MESSAGE";

Intent intent = new Intent(this,


SecondActivity.class);
String message = "Hello Activity!";
intent.putExtra(EXTRA_MESSAGE_KEY, message);
startActivity(intent);

15
Get data from intents

● getData();
⇒ Uri locationUri = intent.getData();
● int getIntExtra (String name, int defaultValue)
⇒ int level = intent.getIntExtra("level", 0);
● Bundle bundle = intent.getExtras();
⇒ Get all the data at once as a bundle.
● See documentation for all

15
Returning data to the starting activity

1. Use startActivityForResult() to start the second Activity


2. To return data from the second Activity:
● Create a new Intent
● Put the response data in the Intent using putExtra()
● Set the result to Activity.RESULT_OK
or RESULT_CANCELED, if the user cancelled out
● call finish() to close the Activity
1. Implement onActivityResult() in first Activity

16
startActivityForResult()

startActivityForResult(intent, requestCode);
● Starts Activity (intent), assigns it identifier (requestCode)
● Returns data via Intent extras
● When done, pop stack, return to previous Activity, and execute
onActivityResult() callback to process returned data
● Use requestCode to identify which Activity has "returned"

16
1. startActivityForResult() Example

public static final int CHOOSE_FOOD_REQUEST = 1;

Intent intent = new Intent(this, ChooseFoodItemsActivity.class);


startActivityForResult(intent, CHOOSE_FOOD_REQUEST);

16
2. Return data and finish second activity

// Create an intent
Intent replyIntent = new Intent();

// Put the data to return into the extra


replyIntent.putExtra(EXTRA_REPLY, reply);

// Set the activity's result to RESULT_OK


setResult(RESULT_OK, replyIntent);

// Finish the current activity


finish();

16
3. Implement onActivityResult()

public void onActivityResult(int requestCode,


int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_REQUEST) { // Identify activity
if (resultCode == RESULT_OK) { // Activity succeeded
String reply =
data.getStringExtra(SecondActivity.EXTRA_REPLY);
// … do something with the data
}}}

16
Navigation

16
Activity stack

● When a new Activity is started, the previous Activity is stopped and pushed on the Activity
back stack
● Last-in-first-out-stack—when the current Activity ends, or the user presses the Back button, it is
popped from the stack and the previous Activity resumes

16
Activity Stack

After viewing v ity


i
ct er
A
r d
shopping cart, user rde e o r
O ac
decides to add more Pl
y a rt
items, then places ti vit ing c v ity g cart
r tAc opp t i
tAc oppin
order. Ca w sh OrderActivity C ar h
Vie i ews
Place order V
CartActivity CartActivity tA ctivity
is
View shopping cart View shopping cart FoodL food items
e
C h oo s
FoodListActivity FoodListActivity FoodListActivity
Choose food items Choose food items Choose food items
MainActivity MainActivity MainActivity MainActivity
What do you want to do? What do you want to do? What do you want to do? What do you want to do?

16
Two forms of navigation

Temporal or back navigation

● provided by the device's Back button


● controlled by the Android system's back stack
Ancestral or up navigation
● provided by the Up button in app's action bar
● controlled by defining parent-child relationships between activities in the Android manifest

16
Back navigation

● Back stack preserves history of recently viewed screens


● Back stack contains all the Activity instances that have been launched by
the user in reverse order for the current task
● Each task has its own back stack
● Switching between tasks activates that task's back stack

16
Up navigation

● Goes to parent of current Activity


● Define an Activity parent in Android manifest
● Set parentActivityName

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

17
Learn more

17
Learn more

● Android Application Fundamentals


● Starting Another Activity
● Activity (API Guide)
● Activity (API Reference)
● Intents and Intent Filters (API Guide)
● Intent (API Reference)
● Navigation

17
What's Next?

● Concept Chapter: 2.1 Activities and Intents


● Practical: 2.1 Activities and intents

17
END

17
Android Developer Fundamentals V2

Activities and
Intents

Lesson 2

This work is licensed under a


Your first
Android Developer Fundamentals V2 Android app
Creative Commons Attribution 4.0 Inter
national License 17175
2.2 Activity lifecycle
and state

17
Contents

● Activity lifecycle
● Activity lifecycle callbacks
● Activity instance state
● Saving and restoring Activity state

17
Activity lifecycle

17
What is the Activity Lifecycle?

● The set of states an Activity can be in during its lifetime,


from when it is created until it is destroyed

More formally:
● A directed graph of all the states an Activity can be in,
and the callbacks associated with transitioning from
each state to the next one

17
What is the Activity Lifecycle?

18
Activity states and app visibility

● Created (not visible yet)


● Started (visible)
● Resume (visible)
● Paused(partially invisible)
● Stopped (hidden)
● Destroyed (gone from memory)

State changes are triggered by user action, configuration


changes such as device rotation, or system action

18
Activity lifecycle
callbacks

18
Callbacks and when they are called

onCreate(Bundle savedInstanceState)—static initialization


onStart()—when Activity (screen) is becoming visible
onRestart()—called if Activity was stopped (calls onStart())
onResume()—start to interact with user
onPause()—about to resume PREVIOUS Activity
onStop()—no longer visible, but still exists and all state info preserved
onDestroy()—final call before Android system destroys Activity

18
Activity states and callbacks graph

18
Implementing and overriding callbacks

● Only onCreate() is required


● Override the other callbacks to change default behavior

18
onCreate() –> Created

● Called when the Activity is first created, for example when user taps launcher icon
● Does all static setup: create views, bind data to lists, ...
● Only called once during an activity's lifetime
● Takes a Bundle with Activity's previously frozen state, if there was one
● Created state is always followed by onStart()

18
onCreate(Bundle savedInstanceState)

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
}

18
onStart() –> Started

● Called when the Activity is becoming visible to user


● Can be called more than once during lifecycle
● Followed by onResume() if the activity comes to the
foreground, or onStop() if it becomes hidden

18
onStart()

@Override
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}

18
onRestart() –> Started

● Called after Activity has been stopped, immediately before


it is started again
● Transient state
● Always followed by onStart()

19
onRestart()

@Override
protected void onRestart() {
super.onRestart();
// The activity is between stopped and started.
}

19
onResume() –> Resumed/Running

● Called when Activity will start interacting with user


● Activity has moved to top of the Activity stack
● Starts accepting user input
● Running state
● Always followed by onPause()

19
onResume()

@Override
protected void onResume() {
super.onResume();
// The activity has become visible
// it is now "resumed"
}

19
onPause() –> Paused

● Called when system is about to resume a previous Activity


● The Activity is partly visible but user is leaving the Activity
● Typically used to commit unsaved changes to persistent data, stop
animations and anything that consumes resources
● Implementations must be fast because the next Activity is not
resumed until this method returns
● Followed by either onResume() if the Activity returns back to the front,
or onStop() if it becomes invisible to the user

19
onPause()

@Override
protected void onPause() {
super.onPause();
// Another activity is taking focus
// this activity is about to be "paused"
}

19
onStop() –> Stopped

● Called when the Activity is no longer visible to the user


● New Activity is being started, an existing one is brought
in front of this one, or this one is being destroyed
● Operations that were too heavy-weight for onPause()
● Followed by either onRestart() if Activity is coming
back to interact with user, or onDestroy() if Activity is
going away

19
onStop()

@Override
protected void onStop() {
super.onStop();
// The activity is no longer visible
// it is now "stopped"
}

19
onDestroy() –> Destroyed

● Final call before Activity is destroyed


● User navigates back to previous Activity, or configuration
changes
● Activity is finishing or system is destroying it to save space
● Call isFinishing() method to check
● System may destroy Activity without calling this, so use
onPause() or onStop() to save data or state

19
onDestroy()

@Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}

19
Activity instance
state

20
When does config change?

Configuration changes invalidate the current layout or other resources in your activity when the user:
● Rotates the device
● Chooses different system language, so locale changes
● Enters multi-window mode (from Android 7)

20
What happens on config change?

On configuration change, Android:

1. Shuts down Activity


by calling:
2. Starts Activity over again
by calling:
● onPause() ● onCreate()
● onStop() ● onStart()
● onDestroy() ● onResume()

20
Activity instance state

● State information is created while the Activity is running,


such as a counter, user text, animation progression

● State is lost when device is rotated, language changes,


back-button is pressed, or the system clears memory

20
Saving and
restoring Activity
state

20
What the system saves

● System saves only:


○ State of views with unique ID (android:id) such as
text entered into EditText
○ Intent that started activity and data in its extras

● You are responsible for saving other activity and user


progress data

20
Saving instance state

Implement onSaveInstanceState() in your Activity

● Called by Android runtime when there is a possibility the


Activity may be destroyed
● Saves data only for this instance of the Activity during
current session

20
onSaveInstanceState(Bundle outState)

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Add information for saving HelloToast counter
// to the to the outState bundle
outState.putString("count",
String.valueOf(mShowCount.getText()));
}

20
Restoring instance state

Two ways to retrieve the saved Bundle


● in onCreate(Bundle mySavedState)
Preferred, to ensure that your user interface, including any saved state, is back up and running as
quickly as possible
● Implement callback (called after onStart())
onRestoreInstanceState(Bundle mySavedState)

20
Restoring in onCreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShowCount = findViewById(R.id.show_count);

if (savedInstanceState != null) {
String count = savedInstanceState.getString("count");
if (mShowCount != null)
mShowCount.setText(count);
}
}
20
onRestoreInstanceState(Bundle state)

@Override
public void onRestoreInstanceState (Bundle mySavedState) {
super.onRestoreInstanceState(mySavedState);

if (mySavedState != null) {
String count = mySavedState.getString("count");
if (count != null)
mShowCount.setText(count);
}
}

21
Instance state and app restart

When you stop and restart a new app session, the Activity instance
states are lost and your activities will revert to their default
appearance

If you need to save user data between app sessions, use shared
preferences or a database.

21
Learn more

● Activities (API Guide)


● Activity (API Reference)
● Managing the Activity Lifecycle
● Pausing and Resuming an Activity
● Stopping and Restarting an Activity
● Recreating an Activity
● Handling Runtime Changes
● Bundle

21
What's Next?

● Concept Chapter: 2.2 Activity lifecycle and state


● Practical: 2.2 Activity lifecycle and state

21
END

21
Android Developer Fundamentals V2

Activities and
Intents
Lesson 2

This work is licensed under a


Your first
Android Developer Fundamentals V2 Android app
Creative Commons Attribution 4.0 Inter
national License 21215
2.3 Implicit Intents

21
Contents

● Intent—recap
● Implicit Intent overview
● Sending an implicit Intent
● Receiving an implicit Intent

21
Recap: Intent

21
What is an Intent?

An Intent is:
● Description of an operation to be performed
● Messaging object used to request an action from another app component via the Android system.

Originator App component

Intent Action
Android
System

21
What can an Intent do?

An Intent can be used to:


● start an Activity
● start a Service
● deliver a Broadcast

Services and Broadcasts are covered in other lessons

22
Explicit vs. implicit Intent

Explicit Intent — Starts an Activity of a specific class

Implicit Intent — Asks system to find an Activity class with a registered handler that can handle this request

22
Implicit Intent
overview

22
What you do with an implicit Intent

● Start an Activity in another app by describing an action you intend to perform, such as "share an
article", "view a map", or "take a picture"
● Specify an action and optionally provide data with which to perform the action
● Don't specify the target Activity class, just the intended action

22
What system does with implicit Intent

● Android runtime matches the implicit intent request with registered intent handlers
● If there are multiple matches, an App Chooser will open to let the user decide

22
How does implicit Intent work?

1. The Android Runtime keeps a list of registered Apps


2. Apps have to register via AndroidManifest.xml
3. Runtime receives the request and looks for matches
4. Android runtime uses Intent filters for matching
5. If more than one match, shows a list of possible matches and lets the user choose one
6. Android runtime starts the requested activity

22
App Chooser

When the Android runtime finds


multiple registered activities that can
handle an implicit Intent, it displays an
App Chooser to allow the user to
select the handler

22
Sending an
implicit Intent

22
Sending an implicit Intent

1. Create an Intent for an action


Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);

User has pressed Call button — start Activity that can make
a call (no data is passed in or returned)

2. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
22
Avoid exceptions and crashes

Before starting an implicit Activity, use the package manager


to check that there is a package with an Activity that matches
the given criteria.

Intent myIntent = new Intent(Intent.ACTION_CALL_BUTTON);

if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}

22
Sending an implicit Intent with data URI

1. Create an Intent for action


Intent intent = new Intent(Intent.ACTION_DIAL);

2. Provide data as a URI


intent.setData(Uri.parse("tel:8005551234"));

3. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}

23
Providing the data as URI

Create an URI from a string using Uri.parse(String uri)

● Uri.parse("tel:8005551234")
● Uri.parse("geo:0,0?q=brooklyn%20bridge%2C%20brooklyn%2C%20ny")
● Uri.parse("http://www.android.com");

Uri documentation

23
Implicit Intent examples

Show a web page


Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = Uri.parse("tel:8005551234");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
23
Sending an implicit Intent with extras

1. Create an Intent for an action


Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);

2. Put extras
String query = edittext.getText().toString();
intent.putExtra(SearchManager.QUERY, query));

3. Start the Activity


if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
23
Category

Additional information about the kind of component to


handle the intent.
● CATEGORY_OPENABLE
Only allow URIs of files that are openable
● CATEGORY_BROWSABLE
Only an Activity that can start a web browser to display
data referenced by the URI

23
Sending an implicit Intent with type and category

1. Create an Intent for an action


Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);

2. Set mime type and category for additional information


intent.setType("application/pdf"); // set MIME type
intent.addCategory(Intent.CATEGORY_OPENABLE);

continued on next slide...

23
Sending an implicit Intent with type and category
3. Start the Activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(myIntent,ACTIVITY_REQUEST_CREATE_FILE);
}

4. Process returned content URI in onActivityResult()

23
Common actions for an implicit Intent

Common actions include:


● ACTION_SET_ALARM
● ACTION_IMAGE_CAPTURE
● ACTION_CREATE_DOCUMENT
● ACTION_SENDTO
● and many more

23
Apps that handle common actions

Common actions are usually handled by installed apps (both


system apps and other apps), such as:

● Alarm Clock, Calendar, Camera, Contacts ➔ List of common


● Email, File Storage, Maps, Music/Video actions for an im
plicit intent
● Notes, Phone, Search, Settings
➔ List of all availab
● Text Messaging and Web Browsing le actions

23
Receiving an
Implicit Intent

23
Register your app to receive an Intent

● Declare one or more Intent filters for the Activity in AndroidManifest.xml


● Filter announces ability of Activity to accept an implicit Intent
● Filter puts conditions on the Intent that the Activity accepts

24
Intent filter in AndroidManifest.xml

<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>

24
Intent filters: action and category

● action — Match one or more action constants


○ android.intent.action.VIEW — matches any Intent with ACTION_VIEW
○ android.intent.action.SEND — matches any Intent with ACTION_SEND

● category — additional information (list of categories)


○ android.intent.category.BROWSABLE—can be started by web browser
○ android.intent.category.LAUNCHER—Show activity as launcher icon

24
Intent filters: data

● data — Filter on data URIs, MIME type


○ android:scheme="https"—require URIs to be https protocol
○ android:host="developer.android.com"—only accept an Intent from
specified hosts
○ android:mimeType="text/plain"—limit the acceptable types of documents

24
An Activity can have multiple filters

<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
...
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE"/>
...
</intent-filter>
</activity> An Activity can have several filters
24
A filter can have multiple actions & data

<intent-filter>
<action android:name="android.intent.action.SEND"/>
<action android:name="android.intent.action.SEND_MULTIPLE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
<data android:mimeType="video/*"/>
</intent-filter>

24
Learn more

24
Learn more

● Intent class documentation


● Uri documentation
● List of common apps that respond to implicit intents
● List of available actions
● List of categories
● Intent Filters

24
What's Next?

● Concept Chapter: 2.3 Implicit Intents


● Practical: 2.3 Implicit Intents

24
END

24
Android Fragments
Fragments

• A Fragment is a piece of an application's user interface or behavior that can be placed in


an Activity which enable more modular activity design.
• A fragment is a kind of sub-activity.
Fragments

• Prior to fragment introduction, we had a limitation because we can show only a single

activity on the screen at one given point in time. So we were not able to divide device

screen and control different parts separately. But with the introduction of fragment we got

more flexibility and removed the limitation of having a single activity on the screen at a

time. Now we can have a single activity but each activity can comprise of multiple

fragments which will have their own layout, events and complete life cycle.
Fragments

• Following are the important points about fragment:


• A fragment has its own layout and its own behavior with its own lifecycle callbacks.
• Add or remove fragments in an activity while the activity is running.
• You can combine multiple fragments in a single activity to build a multi-pane UI.
• A fragment can be used in multiple activities.
• Fragment life cycle is closely related to the lifecycle of its host activity which means when the
activity is paused, all the fragments available in the activity will also be stopped.
• A fragment can implement a behavior that has no user interface component.
Fragments

• You create fragments by extending Fragment class and You can insert a fragment into
your activity layout by declaring the fragment in the activity's layout file, as
a <fragment> element.
Fragments for a Handset or Mobile

Note: On a handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and
when the user selects an article, it starts Activity B, which includes the second fragment to read the article.
Fragments for a Tablet

Note: An application can embed two fragments in Activity A, while running on a tablet-sized device.
Fragment Life Cycle

• Android fragments have their own life cycle very similar to an android activity. This
section briefs different stages of its life cycle.
Fragment Methods (Cont…)

• onAttach()

The fragment instance is associated with an activity


• onCreate()
The system calls this method when creating the fragment.
• onCreateView()
The system calls this callback when it's time for the fragment to draw its user interface for the first time.
• onActivityCreated()
This method is called when the host activity is created. Activity and fragment instance have been created as
well as the view hierarchy of the activity.
Fragment Methods (Cont…)

• onStart()
This method is called once the fragment gets visible.
• onResume()
Fragment becomes active.
• onPause()
The system calls this method as the first indication that the user is
leaving the fragment.
• onStop()
Fragment Methods

• onDestroyView()
Fragment view will destroy after call this method.
• onDestroy()
This method is called when final clean up of the fragment state.
• onDetach()
The fragment instance is disassociated with an activity.
Types of Fragments

• There are three stages of fragments;


• Single Frame or Web View Fragments are using for hand hold devices like mobiles, here we
can show only one fragment as a view.
• List Fragments having specially organized for list view is called as list fragment.
• Fragment Transaction means that we can move one fragment to another fragment.
Example: Single Frame Fragment

• This example will explain you how to create your own Single Frame
Fragment. We will create two fragments and one of them will be used
when device is in landscape mode and another fragment will be used in
case of portrait mode. Follow the following steps to create Single Frame
Fragment.
Step 1: MainActivity.java

• Following is the content of the modified main activity file;


package com.example.fragmentdemo;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){
LM_Fragment ls_fragment = new LM_Fragment();
fragmentTransaction.replace(android.R.id.content,ls_fragment);
}
else{
PM_Fragment pm_fragment = new PM_Fragment();
fragmentTransaction.replace(android.R.id.content,pm_fragment);
}
fragmentTransaction.commit();
}
}
Step 2: LM_Fragment.java

package com.example.fragmentdemo;
• Following is the content of LM_Fragement.java file
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LM_Fragment extends Fragment {


@Nullable
@Override
public View onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.lm_fragment,container,false);
}
}
Step 3: PM_Fragment.java

package com.example.fragmentdemo;
• Following is the content of PM_Fragement.java file
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class PM_Fragment extends Fragment {


@Nullable
@Override
public View onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.pm_fragment,container,false);
}
}
Step 4: lm_fragment.xml

• Create layout files lm_fragement.xml under res/layout directory.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
• Following is the content"http://schemas.android.com/apk/res/android"
of lm_fragement.xml file.
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#968488">
<TextView
android:layout_width="fill_parent“
android:layout_height="wrap_content"
android:text="@string/landscape_message"
android:id="@+id/textView"
android:textSize="60px"
android:textColor="#ffffff" />
</LinearLayout>
Step 5: pm_fragment.xml

• Create layout files pm_fragment.xml under res/layout directory.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
• Following is the content of pm_fragement.xml file
"http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f30606">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/portrait_message"
android:id="@+id/textView2"
android:textSize="60px"
android:textColor="#ffffff"/>
</LinearLayout>
Step 6: activity_main.xml
• Following will be the content of res/layout/activity_main.xml file which
includes your fragments;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="horizontal"
tools:context="com.example.fragmentdemo.MainActivity">
<fragment
android:name="com.example.fragmentdemo.LM_Fragment"
android:id="@+id/lm_fragment“
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment
android:name="com.example.fragmentdemo.PM_Fragment"
android:id="@+id/pm_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent"/>

</LinearLayout>
Step 7: strings.xml

• Following<resources>
will be the content of res/values/strings.xml file
<string name="app_name">FragmentDemo</string>
<string name="landscape_message">This is Landscape Fragment</string>
<string name="portrait_message">This is Portrait Fragment</string>
</resources>
Output: Emulator Window

• When application run following screen will appear


Output: Emulator Window

• To change the mode of the emulator screen, do the following;


• fn+control+F11 on Mac to change the landscape to portrait and vice versa.
• ctrl+F11 on Windows.
• ctrl+F11 on Linux.

You might also like