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

Starting With Android Program

This document provides an overview of key concepts for getting started with Android programming. It discusses layouts and views, and how activities contain UI components that are subclasses of View and ViewGroup. It also covers creating string and color resources, accessing views in activities, and common view components like TextView, EditText, Button, ToggleButton, CheckBox and their usage in XML layouts and Java code. Finally, it briefly introduces concepts like activity lifecycles, multiple activities, intents, lists, dialogs and fragments.

Uploaded by

isac abram
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Starting With Android Program

This document provides an overview of key concepts for getting started with Android programming. It discusses layouts and views, and how activities contain UI components that are subclasses of View and ViewGroup. It also covers creating string and color resources, accessing views in activities, and common view components like TextView, EditText, Button, ToggleButton, CheckBox and their usage in XML layouts and Java code. Finally, it briefly introduces concepts like activity lifecycles, multiple activities, intents, lists, dialogs and fragments.

Uploaded by

isac abram
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Chapter Two

Getting Started With Android


Programming
2. Getting Started with Android
Programming
Topics Covered
 Layout
 Views and View Groups
 How to create String and color files
 Accessing Views in Activity
 Difference between View Groups
 How to create Menu
 Activity
• Activity Life Cycle
 Multiple Activities and Intent
• pass and exchange information b/n Multiple activities
 List Views and Adapters
 Dialogs
 Fragments
The activities will contain a multiple UI components and those UI components are the instances of View and ViewGroup subclasses.

Views and View Groups

 A layout defines what a screen looks like (user Interface) defined


using XML
 Layouts usually contain GUI components such as buttons and text
fields
 the android apps will contain one or more activities and each
activity is a one screen of app.
 The user interface in android app is made with a collection of view
and view Groups
 All layouts and GUI components are subclasses of the Android View
class
Cont’d
 A GUI component(widget) is a type of view, an object that takes up space
on the screen . View is a base class for all GUI components in android.
 View refer to the android.view.View class.
 TextView
 EditText
 Button
 CheckBox
 RadioButton
 ImageButton
 Progress Bar
 Spinner
Cont’d

 View Group: A view group is a type of view that can contain other
views.
 A layout is a special type of view called a view group.
 All layouts are subclasses of the android.view.ViewGroup class.
 All layouts and GUI components share this common functionality.
 Linear Layout
 Relative Layout
 Constraint Layout
 Frame Layout
 Web View
 List View
 Grid View
String.xml and Color.xml
 strings.xml is a String resource file. It includes Strings such as the app’s
name and any default text values. Other files such as layouts and
activities can look up text values from here.
How do you use String resources?
In order to use a String resource in your layout, there are two things
you need to do:
1) Create the String resource by adding it to strings.xml.
2) Use the String resource in your layout.
To do this, use Android Studio’s explorer to find the file strings.
xml in the app/src/main/res/values folder. Then open it by double-
clicking on it.
<resources>
<string name=“age">Enter your Age</string>
</resources>

This indicate that


This indicate the This indicate the
this is a string
name of the string value of the string
resource files
resource file resource file
Use the String resource in your layout
android:text="@string/age" />
@string - telling Android to look up a text value from a String resource
file.
The second part, name, tells Android to look up the
value of a resource with the name age.
Why we need Strings.xml
 We can list two reasons that we need strings.xml
1) Hardcoding text makes localization hard
2) To make global changes to the text.
Scenario #1
You don’t want to limit yourself to just one country or language—you want
to make it available internationally and for different languages. But if
you’ve hardcoded all of the text in your layout files, sending your app
international will be difficult.
Scenario #2
Imagine your boss asks you to change the wording in the app because
the company’s changed its name. If you’ve hardcoded all of the text, this
means that you need to edit a whole host of files in order to change the
text.
 Colors.xml: colors are usually stored in a resource file name
colors.xml in the res/values/ folder.
 We will follow a same procedure with Strings.xml
In order to use a color resource in your layout, there are two things
you need to do:
1) Create the color resource by adding it to colors.xml.
2) Use the color resource in your layout.
<resources>
<color name=“colorprimary">#3F51B5</color>
</resources>
Use the Color resource in your layout
android:background="@color/ colorprimary" />
Most Common View Components
 Text View: A text view is used for displaying text.
Here is how to define a Text view in XML
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text" />
We can define the text size by using
android:textSize=“16sp”
Scale-independent pixels take into account whether users want to use large fonts on their
devices.

Activity Code for Accessing Text View


TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText("Some other String");
 Editable text view (Edit Text): This is like a text view, but editable. We can use it incase of letting
the user to enter information.
Value Function
Here is how to define a Edit Text in XML
Phone Provides a phone number keypad
<EditText
textPassword Displays a text entry keypad, and your
android:id="@+id/edit_text" input is concealed.
android:layout_width="wrap_content" textCapSentences Capitalizes the first word of a sentence.
android:layout_height="wrap_content" textAutoCorrect Automatically corrects the text being
android:hint="@string/edit_text" /> input.

To define what type of data you’re expecting the user to enter we can use
android:inputType="number“
You can specify multiple input types using the | character
E.G android:inputType="textCapSentences|textAutoCorrect"

Activity Code for Accessing Edit Text


EditText editText = (EditText) findViewById(R.id.edit_text);
String text = editText.getText().toString();
 Button: Buttons are usually used to make your app do something when they’re clicked
Here is how to define a Button in XML
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text" />
We can respond to the user click by using android:onClick=“onButtonClicked”

Activity Code for define method


/* Called when the button is clicked */
public void onButtonClicked(View view) {
// Do something in response to button click
}
 Toggle Button : A toggle button allows you to choose between two states by clicking a
button.
 Here is how to define a Toggle Button in XML
Activity Code for Defining Method
<ToggleButton
/** Called when the toggle button is
android:id="@+id/toggle_button" clicked */
android:layout_width="wrap_content" public void onToggleButtonClicked(View
view) {
android:layout_height="wrap_content"
// Get the state of the toggle button.
android:textOn="@string/on" boolean on = ((ToggleButton)
android:textOff="@string/off" /> view).isChecked();
if (on) {
We can respond to the user click by using the same procedure
// On
like Button android:onClick=“onToggleButtonClicked” } else {
// Off
}
}

Switch View Component is similar with Toggle Button a


slider control that acts in the same way as a toggle
button.
 Check Boxes: let you display multiple options to users. They can then select
whichever options they want. Each of the checkboxes can be checked or
unchecked independently of any others
Here is how to define a Check Boxes in XML
<CheckBox android:id="@+id/checkbox_milk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/milk“
android:onClick="onCheckboxClicked"
/>
<CheckBox android:id="@+id/checkbox_sugar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sugar“
android:onClick="onCheckboxClicked"
Cont’d
 Activity Code for Accessing Check Box
public void onCheckboxClicked(View view) {
// Has the checkbox that was clicked been checked?
boolean checked = ((CheckBox) view).isChecked();
// Retrieve which checkbox was clicked
switch(view.getId()) {
case R.id.checkbox_milk:
if (checked)
//
else
//
break;
case R.id.checkbox_sugar:
if (checked)
//
else
//
break;
}
}
 Radio Button: These let you display multiple options to the user. The user can select a
single option.
Here is how to define a Radio Button in XML
<RadioGroup android:id="@+id/radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Male“
android:onClick="onRadioButtonClicked"
/>
<RadioButton android:id="@+id/radio_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Female"
android:onClick="onRadioButtonClicked"
/>
</RadioGroup>
Cont’d
 Activity Code for Accessing RadioButton
public void onRadioButtonClicked(View view) {
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
int id = radioGroup.getCheckedRadioButtonId();
switch(id) {
case R.id.radio_male:
//
break;
case R.id.radio_female:
//
break;
}
}
 Spinner: a spinner gives you a drop-down list of values
from which only one can be selected. String.xml
Here is how to define a Spinner in XML <string-array name="spinner_values">
<item>Red</item>
<Spinner <item>White</item>
android:id="@+id/spinner" <item>Black</item>
<item>Blue</item>
android:layout_width="wrap_content" </string-array>
android:layout_height="wrap_content"
android:entries="@array/spinner_values“ />

Activity Code for Accessing Selected Item


Spinner spinner = (Spinner) findViewById(R.id.spinner);
String string = String.valueOf(spinner.getSelectedItem());
 Image View: image view is used to display an image.
Adding an Image
We need to create a drawable resource folder
In res directory, go to File menu, choose the New... option, then click on the option to
create a new Android resource directory. When prompted, choose a resource type of
“drawable”, name the folder “drawable”, and click on OK. You then need to add your
image to the app/src/main/res/drawable folder.

Folders for different screen densities


drawable-ldpi Low-density screens, around 120 dpi.
drawable-mdpi Medium-density screens, around 160 dpi.
drawable-hdpi High-density screens, around 240 dpi.
drawable-xhdpi Extra-high-density screens, around 320 dpi.
drawable-xxhdpi Extra-extra-high-density screens, around 480 dpi.
drawable-xxxhdpi Extra-extra-extra high-density screens, around 640 dpi.
 Here is how to define a Image View in XML
<ImageView
android:layout_width="200dp"
android:layout_height="100dp"
android:src="@drawable/logo"
android:contentDescription="@string/logo" />

Activity Code for Accessing Selected Item


ImageView photo = (ImageView)findViewById(R.id.photo);
int image = R.drawable.logo;
String description = "This is the logo";
photo.setImageResource(image);
photo.setContentDescription(description);
 Displaying text and an image on a button
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableRight="@drawable/android"
android:text="@string/click_me" />

Define Image Button in xml


<ImageButton
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/button_icon" />
 Scroll view: If you add lots of views to your layouts, you may have problems on devices with
smaller screens. As an example, when we add seven large buttons to a linear layout, we
couldn’t see all of them.
To add a vertical scrollbar to your layout, you surround your existing layout with a <ScrollView>
element like this:
Vertical Scroll Bar
<ScrollView
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="com.hfad.views.MainActivity" > N.B
To add a horizontal scrollbar to your
<LinearLayout layout, wrap your existing
android:layout_width="match_parent" layout inside a <HorizontalScrollView>
android:layout_height="match_parent"
element instead.
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:orientation="vertical" >
...
</LinearLayout>
 Toast: A toast is a simple pop-up message you can display on the
screen. While a toast is displayed, the activity stays visible and
interactive. The toast automatically disappears when it times out.
N.B you can create Toast using activity code only. isn't actually a
type of view.
Activity code for display Toast
Using Toast.makeText() methos
CharSequence text = "Hello, I'm a Toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.show();

It take three Parameters


- A Context (usually this for the current
activity)
- a Char Sequence that’s the message you want to display
- - int duration
Exercise
 Try to create this layout

Enter your name (Edit Text)

Submit (Button)

 Display the input text (Text View)


 Use Toast to display the name
Most Common View Groups
 View Group is generally used to define the layout in which
views(widgets) will be set/arranged/listed on the android screen.
 Linear Layout: displays its views next to each other, either vertically or
horizontally. If it’s vertically, the views are displayed in a single column. If
it’s horizontally, the views are displayed in a single row.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
...>
...
</LinearLayout>
 The layout_width and layout_height specify what size you want the
layout to be.
 These attributes are mandatory for all types of layout and view.
 The orientation specifies whether you want to display views vertically
or horizontally.
 The xmlns:android attribute is used to specify the Android
namespace
 "wrap_content" means that we want the layout to be just big
enough to hold all of the views inside it.
 "match_parent" means that we want the layout to be as big as its
parent
 Padding: will add a bit of space around the edge of layout. It is also called push inside.
The view pushes its contents from itself by the dimension specified in the padding
attribute
android: padding=“16dp” {This adds the same padding to all edges of the layout.} Top, Bottom,
Left, Right
But we can specify the padding from each edges.
<LinearLayout ...
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="32dp" >
...
</LinearLayout>
 Margins: we will use Margins to add distance between views. It is called push outside. The view
pushes its surrounding contents from itself by the dimension specified in the margin attribute.
Android:layout_margin= “20dp”

 In Android, padding attribute applied to the parent(root layout) looks the same
as margin attribute applied to the child(views inside the layout).
 Gravity: controls the position of a view’s contents. We can achieve this by using android:gravity
attribute.
 The android:gravity attribute lets you specify how you want to position the contents of a view inside
the view.
 <LinearLayout ... >
...
<Button
android:layout_width="match_parent"
android:layout_height=“wrap_content"
android:gravity="top"
android:hint="@string/message" />
...
 </LinearLayout>
 Displays the text inside the Button at the top of the Button
 Layout_gravity: controls the position of a view within a layout. We can achieve this by using
android:layout_gravity attribute.
 android:layout_gravity deals with the placement of the view itself, and lets you control where views
appear in their available space.
 Android:layout_gravity=“end”
 Linear Layout supports assigning a weight to individual children with
the android:layout_weight attribute.
 This attribute assigns an "importance" value to a view in terms of how
much space it should occupy on the screen. A larger weight value
allows it to expand to fill any remaining space in the parent view.
 Try to develop the layout the next Layout
Linear Layout Example
Relative Layout

 Relative Layout: is a view group that displays child views in relative


positions. The position of each view can be specified as relative to
sibling element (such as to the left-of or below another view) or in
positions relative to the parent Relative Layout area (such as
aligned to the bottom, left or center).
 A Relative Layout is a very powerful utility for designing a user
interface because it can eliminate nested view groups and keep
your layout hierarchy flat. which improves performance
 If you find yourself using several nested Linear Layout groups, you
may be able to replace them with a single Relative Layout
Attributes for relative layout

 android:layout_alignParentTop
If “true”, makes the top edge of this view match the top edge of the
parent
 android:layout_centerVertical
If “true”, centers this child vertically within its parent
 android:layout_below
Positions the top edge of this view below the view specified with a
resource ID.
 android:layout_toRightOf
Positions the left edge of this view to the right of the view specified with
a resource ID.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<TextView
android:id="@+id/sign_in"
android:layout_width=“wrap_content" Sign in (TextView)
android:layout_height="wrap_content“
android:layout_alignParentTop=“true”
android:layout_centerHorizontal=“true” (TextView)UserName: enter user name(Edit Text)
/> (TextView)Password: enter Password(Edit Text)
<TextView
android:id="@+id/user_name"
android:layout_width=“wrap_content" Login
android:layout_height="wrap_content"
android:layout_below="@id/sign_in"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/txt_user" />
<TextView
android:id="@id/password"
android:layout_width=“wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/user_name"
/>
<Button
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/pasword"
android:layout_centerHorizontal="true"
/>
Frame Layout
 We use Frame Layout when we want our views to overlap. For
instance suppose we want to display an image with some text
overlaid on top of it.
 Frame Layout stack their views on top of each other.
 Frame Layout is designed to block out an area on the screen to
display a single item
 We define Frame Layout using <FrameLayout> element.
 The android:layout_width and android:layout_height attributes are
mandatory
 it can be difficult to organize child views in a way that's scalable to
different screen sizes without the children overlapping each
other. But we can control their position using android:layout_gravity.
Constraint Layout
 Constraint Layout: Constraint Layout is a View Group (i.e. a view that
holds other views) which allows you to create large and complex
layouts with a flat view hierarchy
 Allows you to position and size widgets in a very flexible way. It was
created to help reduce the nesting of views and also improve the
performance of layout files.
Advantage
 you can perform animations on your Constraint Layout views with very
little code.
 You can build your complete layout with simple drag-and-drop on
the Android Studio design ed
 You can control what happens to a group of widgets through a single
line of code.
 Dynamically position UI elements onscreen in relation to other elements.
 Constraint Layout improve performance over other layout
 Important points to use constraint Layout
 Your Android Studio version must be 2.3 or higher.
 You must first include the ConstraintLayout’s support library.
 You must have at least one vertical and one horizontal constraints.

In general, Constraint Layout is a faster, better and much more


efficient choice to designing large and complex layouts in your
Android UI.
Menu
 Menu is a part of the user interface (UI) component which is used to
handle some common functionality around the application.
 By using Menus in our applications, we can provide familiar and
consistent user experience throughout the application.
 Instead of building a menu in your activity's code, you should define a
menu and all its items in an XML menu resource and load menu
resource as a Menu object in our activity.
We can list some reasons
Cont’d

 It's easier to visualize the menu structure in XML.


 It
separates the content for the menu from your application's
behavioral code.
 Itallows you to create alternative menu configurations for
different platform versions, screen sizes, and other
configurations by leveraging the app resources framework.
 To define Menu
in the app/src/main/res folder, choose
File -> New -> Layout Resource File -> Menu
Types of Menu

 In android, we have a three fundamental type of Menus available


to define a set of options and actions in our android applications.
 Options Menu
 Context Menu
 Popup Menu
 Options Menu: In android, Options Menu is a primary collection of
menu items for an activity and it is useful to implement actions that
have a global impact on the app, such as Settings, Search,
compose email etc.
Option Menu xml & Activity

 XML

Activity code
@Override
<menu xmlns:android="http://schemas.android.com/apk/res/and public boolean
roid"> onCreateOptionsMenu(Menu
menu) {
getMenuInflater().inflate(R.menu.a
<item android:id="@+id/search" ctivity_main, menu);
android:title="@string/search"
return true;
/>
}
<item android:id="@+id/settings"
android:title="@string/settings" />
</menu>
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.search:
Toast.makeText(getApplicationContext(),“search Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.settings:
Toast.makeText(getApplicationContext(),“settings Selected",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
 Context Menu: is like a floating menu and that appears when the
user performs a long press or click on an element and it is useful to
implement actions that affect the selected content or context
frame.
 Mostly used in List views and Grid views
 The views which are used to show the context menu on long-press
need to registered using registerForContextMenu(view)
 we need to override onCreateContextMenu() in our Activity
or Fragment to display the context menu on the view.
 we can handle a context menu item click events using the
onContextItemSelected() method.
Context Menu Xml & Activity
 Xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/sms"
android:title="@string/send_sms"
/>
<item android:id="@+id/copy"
android:title="@string/copy" />
</menu>

@override
 Activity Public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo){
Super.onCreateContextMenu(menu,v,menuInfo);
MenuInflater inflater= getMenuInflator();
Inflator.inflate(R.menu.context_menu, menu);

}
Cont’d
 We will create List View and register it on our ContextMenu
String names={“”,””,””}
ListView list;
list= (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.
simple_list_item_1,names);
listView.setAdapter(adapter);
registerForContextMenu(listView); // Register the ListView for Context menu
 Next we can handle a context menu item click events using the
onContextItemSelected() method.
 @Override
public boolean onContextItemSelected(MenuItem item){
if(item.getItemId()==R.id.sms){
Toast.makeText(getApplicationContext(),“sms code",Toast.LENGTH_LONG).sho
w();
}
else if(item.getItemId()==R.id.copy){
Toast.makeText(getApplicationContext(),“copy code",Toast.LENGTH_LONG).sho
w();
}else{
return false;
}
return true;
}
}
 Popup Menu: displays a list of items in a modal popup window that
is anchored to the view. The popup menu will appear below
the view if there is a room or above the view in case if there is no
space and it will be closed automatically when we touch outside of
the popup.it is useful to provide an overflow of actions that related
to specific content.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/one"
android:title="One" />
<item
android:id="@+id/two"
android:title="Two"/>
<item
android:id="@+id/three"
android:title="Three"/>
</menu>
@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());

//registering popup with OnMenuItemClickListener


popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});

popup.show();//showing popup menu


}
});//closing the setOnClickListener method
}
Activity
 An App is a collection of activities, layouts, and other resources.
 One of the activities is the main activity for the app.
 By default, each app runs within its own process.
 This helps keep your apps safe and secure. If the system identifies that
resources on the device are reaching capacity it will take steps to
terminate processes to free up memory.
 When an activity needs to start, Android checks whether there’s already
a process for that app.
 If one exists, Android runs the activity in that process. If one doesn’t exist,
Android creates one.
 When Android starts an activity, it calls its onCreate() method.
 onCreate() is always run whenever an activity gets created.
Cont’d
 An activity will interact with the UI component (User Interface) by
using setContentView(View)
 An activity provides the window in which the app draws its UI.
 Generally one activity implements one(single) screen in an app.
 To use activities in your app, you must register information about
them in the app’s manifest, and you must manage activity lifecycles
appropriately.
 The life cycle states (and callbacks) are per activity not per
application, so we can implement different behavior at different
points in the lifecycle of each Activity.
 Next, the Activity Stack and life cycle will be discussed
Activity Stack
 For each application that is running on an Android device, the runtime
system maintains an Activity Stack.
 When an application is launched, the first of the application’s activities
to be started is placed onto the stack.
 When a second activity is started, it is placed on the top of the
stack and the previous activity is pushed down.
Life Cycle of Android Activity
Method When it is called NextMethod
onCreate() When the activity is first created. It also gives you a Bundle onStart()
that contains the previously saved state of the activity.

onRestart() When your activity has been stopped but just before it gets onStart()
started again.
onStart() When your activity is becoming visible. onResume() or
onStop()
onResume() When your activity is in the foreground. onPause()
onPause() When your activity is no longer in the foreground because onResume() or
another activity is resuming onStop()

onStop() When the activity is no longer visible onRestart() or


onDestroy()
onDestroy() When your activity is about to be destroyed or None
because the activity is finishing.

Fig Visual Representation of the Activity lifecycle


 This are some examples that shows when call backs methods will be
called
 On Pause:
 Some event interrupts app execution, like receiving a phone
call, the user’s navigating to another activity, or the device
screen’s turning off.
 InAndroid 7.0 (API level 24) or higher, multiple apps run in
multi-window mode. Because only one of the apps (windows)
has focus at any time, the system pauses all of the other apps.
A new, semi-transparent activity (such as a dialog) opens. As
long as the activity is still partially visible but not in focus, it
remains paused.
Cont’d
 On Stop
 when a newly launched activity covers the entire screen
 The user navigates to the device’s home screen

 On Destroy
 theactivity is finishing (due to the user completely dismissing
the activity)
 the
system is temporarily destroying the activity due to a
configuration change (such as device rotation, language)
Stop Watch Activity
 Layout
Cont’d
 Use

Linear Layout
 Relative Layout or
Constraint Layout
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
 Activity code public class StopwatchActivity extends Activity {
private int seconds = 0;
private boolean running;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
}
//Start the stopwatch running when the Start button is clicked.
public void onClickStart(View view) {
running = true;
}
//Stop the stopwatch running when the Stop button is clicked.
public void onClickStop(View view) {
running = false;
}
//Reset the stopwatch when the Reset button is clicked.
public void onClickReset(View view) {
running = false;
seconds = 0;
}
}
 A Handler is an Android class you can use to schedule code that should
be run at some point in the future private void runTimer() {
 To use the Handler, you wrap the code you wish to final TextView timeView =
(TextView)findViewById(R.id.time_view
schedule in a Runnable object, and then use the );
Handler post() and postDelayed() methods to specify final Handler handler = new Handler();
handler.post(new Runnable() {
when you want the code to run. @Override
 The post() method posts code that needs to be run as public void run() {
int hours = seconds/3600;
soon as possible (which is usually almost immediately). int minutes = (seconds%3600)/60;
This method takes one parameter, an object of type int secs = seconds%60;
String time =
Runnable. String.format(Locale.getDefault(),
 The postDelayed() method works in a similar way to the "%d:%02d:%02d", hours, minutes, secs);
timeView.setText(time);
post() method except that you use it to post code that
if (running) {
should be run in the future seconds++;
}
Two parameters: A Runnable and a long
handler.postDelayed(this, 1000);
}
});
Cont’d
 Your Activity inherits the lifecycle methods
 Context: An interface to global information
about the application environment allows access
to application resources, classes, and operations.
 Activity: The Activity class implements default
versions of the lifecycle methods. It also defines
methods such as findViewById(Int) and
setContentView(View).
States of an Activity
 The main state of an activity is when it’s running or active. An activity is running
when it’s in the foreground of the screen, it has the focus, and the
user can interact with it. Activity
Launched
 The onCreate() method gets called immediately after your
activity is launched. This method is where you do all your normal
activity setup such as calling setContentView()
 The onDestroy() method is the final call you get before the
Activity
activity is destroyed. There are a number of situations in which
Running
an activity can get destroyed
—for example, if it’s been told to finish, if the activity is being recreated due to a
change in device configuration, or if Android has decided to destroy the activity in
order to save space.
Activity
Destroyed
Save the current state (onCreate/
onDestroy)

 When we change device configuration, like orientation the app will loss
local variables used by the activity.
 How we restore the value?
 We need to implement the onSaveInstanceState() method. This
method gets called before the activity gets destroyed, which means
you get an opportunity to save any values you want to retain before
they get lost.
 onSaveInstanceState() method takes one parameter, a Bundle. A
Bundle allows you to gather together different types of data into a
single object.
public void onSaveInstanceState(Bundle savedInstanceState) {
}
 Add this two codes in the activity

Save the values of the Restore the state in onCreate.


seconds and running protected void onCreate(Bundle
variables to the Bundle. savedInstanceState) {
@Override super.onCreate(savedInstanceState);
public void setContentView(R.layout.activity_stopwatch);
onSaveInstanceState(Bundle if (savedInstanceState != null) {
savedInstanceState) { seconds =
savedInstanceState.putInt("seconds", savedInstanceState.getInt("seconds");
seconds); running =
savedInstanceState.putBoolean("runni savedInstanceState.getBoolean("running");
ng", running); }
} runTimer();
}
 There are additional lifecycle methods which deal with activity’s
visibility. onStart(), onStop(), and onRestart()
 We inherit from Android Activity class like onCreate() and
onDestroy().
 onStart() gets called when your activity becomes visible to the user.
 onStop() gets called when your activity has stopped being visible to
the user. This might be because it’s completely hidden by another
activity that’s appeared on top of it
 onRestart() gets called after your activity has been made invisible,
before it gets made visible again.
Implement onStop() to stop the
timer
 We have to add a new variable to record whether the stopwatch
was running before the onStop() method was called so that we
know whether to set it running again when the activity becomes
visible again.
@Override
@Override
protected void onStart() {
protected void onStop() {
super.onStart();
super.onStop();
if (wasRunning) {
wasRunning = running;
running = true;
running = false;
}
}
}

 savedInstanceState.putBoolean("wasRunning", wasRunning);
 wasRunning = savedInstanceState.getBoolean("wasRunning");
Implement onPause() to stop the
timer
 When an activity is visible but doesn’t have the focus, the activity is
Paused. This can happen if another activity appears on top of your
activity that isn’t full-size or that’s transparent.

@Override
@Override
protected void onResume() {
protected void onPause() {
super.onResume();
super.onPause();
if (wasRunning) {
wasRunning = running;
running = true;
running = false;
}
}
}
Conclusion
 Properly use the Activity Life cycle can help ensure that your app
avoids:
 Consuming valuable system resources when the user is not
actively using it.
 Losing the user’s progress if they leave your app and return to it
at a later time.
 Crashing or losing the user’s progress when the screen rotates
between landscape and portrait orientation or switches to
another app while using your app.
Intent
 Apps can contain more than one Activity
 For example, if your app is simple it can display a list of recipes.
But most of time, you will need to use multiple activities one for
displaying the list of recipes and another for adding a single recipe.
 You start an activity by creating an intent and using it in the
startActivity() method.
 Android Intent is the message that is passed between components
such as activities, content providers, broadcast receivers, services
etc. The dictionary meaning of intent is intention or purpose. So, it
can be described as the intention to do action.
 A messaging app could start an activity in a camera app to take a
picture, then start an activity in an email app to let the user share the
picture in email.
Intent Applications

 Generally using intents we can achieve:


 Sending the User to Another App
 Getting a Result from an Activity
 Allowing Other Apps to Start Your Activity
 Start
App Components (Activities, Services, send
broadcast ).
Types of Intent
 Two types of intent
i) Implicit intent
ii) Explicit intent
Implicit intent: Implicit Intent doesn't specify the component(). In such
case, intent provides information of available components provided
by the system that is to be invoked.
 When you use an implicit intent, Android uses the information in the
intent to figure out which components are able to receive it. So you
leave the details of which activity performs it to Android. Android
does this by checking the intent filters in every app’s copy of
AndroidManifest.xml.
Cont’d
 Intent Filters: specify the kind of Intent your activity will accept.
Intent filters may contain the following three elements
<action>: The Intent action that the activity accepts
<data>: The type of data accepted by activity. The data can be represented by
MIME type or other attributes of the data URI.
<category>: the intent category
 The main activity of your app needs an Intent filter that defines the “main”
action and the “launcher” category so the system can launch your app.

<intent-filters> This specifies that this is the


<action android:name=“android.intent.action.MAIN” /> app’s “main” entry point
<category
This activity should be listed
android:name=“android.intent.category.LAUNCHER” />
in the systems app launcher
Intent Action Types
 Our Application can request different action depending on our
interest.
 This are commonly used Action Types
Action Type Description
ACTION_CALL Brings up a phone dialer and immediately initiates a call
using the number supplied in the Intent’s data URI
ACTION_SEND Also known as the share intent, when you have some data
that the user can share through another app, such as an
email app or social sharing app.
ACTION_VIEW when you have some information that an activity can show
to the user. E.g webpages, photos
Intent Filter Example
E.g. Here’s the entry for an activity that can handle an action of ACTION_SEND.
The activity is able to accept data with MIME types of text/plain or image:
<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"/>
<data android:mimeType="image/*"/>
</intent-filter>
</activity>
N.B If an Activity does not include Intent filters, it can only be launched with an
explicit intent
Any Activity that you want to accept an implicit intent must include the
android.intent.category.Default intent filter
Implicit Intent Example

 The intent requests applications that can handle send action


having textual data.

Intent intent = new If you always want your user to choose an Activity
Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain"); intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, intent.putExtra(Intent.EXTRA_TEXT, "Hello");
"Hello"); String chooserTitle = getString(R.string.chooser);
startActivity(intent) Intent chosen= Intent.createChooser(intent,chooserTitle);
startActivity(chosen);
Explicit Intent
 Explicit intent: Explicit Intent specifies the component. In such case,
intent provides the external class to be invoked in our app. We are
explicitly tell Android which class is expected to run.
 Explicit Intent work internally within an application to perform navigation
and data transfer.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
Create the second activity and
layout
 In the app/src/main/java folder, choose
 File → New → Activity, and choose the option for Empty Activity.
You will be presented with a new screen where you can choose
options for your new activity.
 Check the activity in AndroidManifest.xml
Let say your First activity is sendMessageActivity and your second
activity is receiveMessageActivity

Send message Activity


public void onSendMessage(View view) {
EditText messageView = (EditText) Receive message Activity
findViewById(R.id.message); Intent intent = getIntent();
String messageText = String messageText =
messageView.getText().toString(); intent.getStringExtra(“message”);
Intent intent = new Intent(this, TextView messageView =
ReceiveMessageActivity.class); (TextView)findViewById(R.id.message);
intent.putExtra(“message”, messageText); messageView.setText(messageText);
startActivity(intent);
}
}
Getting data from Activity
 The steps to get result from Activity
 We use Start Activity for result with the Intent and a Request
code
 Create a new Intent in the launched activity and add the
return data to that intent
 Implement onActivityResult in the original activity to process
the returned data
 In most cases this method takes two parameters; intent object and request
code. To pass the information to another activity and to uniquely identify our
request to that activity respectively.
 The request code is an integer that identifies the request and can be used to
differentiate between results when you process the return data
For e.g. if you launch one activity to take a photo and another to pick a
photo from a gallery, we need different request codes to identify which
request the returned data belongs to.
 Our Activity needs to override onActivityResult method that is invoked automatically when the
second activity returns result.
onActivityResult() method
 The three arguments to onActivityResult() contain all the information you
need to handle the return data.

 Request code: The request code you set when you launched
the Activity with startActivityForResult()

 Result code: the result code set in the launched Activity, usually
one of RESULT_OK or RESULT_CANCELED

 Intent data: The intent that contains the data returned from the
launched Activity.

 In the next, we will see how we get results from an activity.


Get Activity class
final int REQUEST_Code = 2;
public void onClick(View view) {
Intent intent = new Intent(this, GiveActivity.class);
intent.putExtra(“message”, messageText);
startActivityForResult(intent,2);
}

Protected void onActivityResult(int requestCode, int resultCode,Intent
intent){
If (requestCode == REQUEST_Code && resultCode == RESULT_OK){
Textview.setText(intent.getStringExtra(“message”));
}
}

Give Activity class


public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra(“message”, “Hi”);
setResult(RESULT_OK,intent);
finish();
}
List View and Adapter
 A list view allows you to display a list of data that you can then use
to navigate through the app.
 ListView is a ViewGroup that is used to display the list of scrollable of
items in multiple rows and the list items are automatically inserted to
the list using an adapter. Each view is positioned immediately below
the previous view in the list.
 An adapter acts as a bridge between a view and a data source. It
reads data from various data sources, coverts it into View objects
and provide it to the linked Adapter view to create UI components..
Define ListView in XML
<LIstView
android:id=“@+id/”
android:layout_width=“”
android:layout_height=“”
android:divider=“@color/”
android:dividerHeight=“” />

 android:divider: we can specify a divider between List items. A


drawable or any color can be specified as a value for this attribute.
 android:dividerHeight: used to specify height of the divider
Organize our Activity
 It is better to partition our ideas in to three different types of activity.
 Top-level Activities
 Category Activities
 Detail/edit Activities

 Top-level Activities: contains the things that are most important to


the user, and gives them an easy way of navigating to those things
In most apps, the first activity the user sees will be a top-level activity.
 Category Activities: show the data that belongs to a particular
category, often in a list. This activities are often used to help the user
navigate to detail/edit activities.
 Detail/edit Activity: displays details for a particular record, let the
user edit the record or allow the user to enter new records.
Types of Adapters
 There are some commonly used Adapter in Android.
 Base Adapter
 Array Adapter
 Custom Array Adapter
 Simple Cursor Adapter

 Base Adapter: is a base class of a general implementation of an Adapter


that can be used in ListView, GridView, Spinner etc.
 we use when we need a customized list in a ListView or customized grids
in a GridView. Base Adapter can be extended to create a Custom
Adapter for displaying a custom list item.

public class CustomAdapter extends BaseAdapter {


@Override public int getCount() { return 0; }
@Override public Object getItem(int i) { return null; }
Override public View getView(int i, View view,
ViewGroup viewGroup) { return null; }
Cont’d
 Array Adapter: is a type of adapter that specializes in working with
arrays.
Array Adapter is used when
 Our data source is array e.g. list of phone contacts, countries
or name
 By default, Array Adapter expects a Layout with a single TextView.
ArrayAdapter creates a view for each item by calling toString() on
each item and place the content in a TextView.
ArrayAdapter constructor takes the following parameters:
ArrayAdapter<String> adapter= new
ArrayAdapter<String>(this,android.R.layout.simple_list_item1,myStringArr
ay)
Cont’d(Array Adapter)
 Context: the reference of current class
 Resource: The layout that contains a TextView for each
string in the array.
 Objects: The String Array.
Then we can simply call SetAdapter() on our ListView:
ListView listView= (ListView) findViewById(your listview id);
listView.SetAdapter(adapter);

Try to create list view that displays list of contacts name

String[] contactsname={};
Cont’d
 N.B. For complex layouts or if there is need to customize our list view
or grid view Array Adapter is not suitable rather use custom
adapters.
 Custom Array Adapters: ArrayAdapter is an implementation of
BaseAdapter, so if we want more customization then we can create
a custom adapter and extend ArrayAdapter on that class.
For e.g
if we want to create a view something other than a TextView like
displaying an image with text for each item, we extend the
ArrayAdapter class and override getView() to return the type of view
you want for each item.
 Simple Cursor Adapter: An easy adapter to map columns from a cursor to
TextViews or ImageViews defined in an XML file. You can specify which columns
you want, which views you want to display the columns, and the XML file that
defines the appearance of these views.

 Used when our data comes from database.

 SimpleCursorAdapter Constructor takes the following parameters

SimpleCursorAdapter adapter = new SimpleCursorAdapter


(this,R.layout.simple_list_item_1,cursor,fromcolumns,toViews,0)

fromcolumns and toviews arrays tells which columns in the cursor to match to which

views
Try This …

Top Level Activity
 xml <LinearLayout
android:orientation=“vertical”>

<ImageView
android:layout_width="200dp"
android:layout_height="100dp"
android:src="@drawable/starbuzz_logo"
android:contentDescription="@string/starbuzz_logo" />

<ListView
android:id="@+id/list_options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/options" />

Strings.xml
<string-array name="options">
<item>Drinks</item>
<item>Food</item>
<item>Stores</item>
Cont’d
 Java
//oncreatemethod
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> listView,
View itemView,
int position,
long id) {
if (position == 0) {
Intent intent = new Intent(TopLevelActivity.this,
DrinkCategoryActivity.class);
startActivity(intent);
}
}
};
//Add the listener to the list view
ListView listView = (ListView) findViewById(R.id.list_options);
listView.setOnItemClickListener(itemClickListener);
}
}
Drink Category Activity
 Xml
<LinearLayout
android:orientation=“vertical”>

<ListView
android:id="@+id/list_drinks"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

 To hold our drink data we will create pure java class


Refer the code Page no. 256 (The Drink class)
//oncreate method
ArrayAdapter<Drink> listAdapter = new ArrayAdapter<>(
this,
Cont’d android.R.layout.simple_list_item_1,
Drink.drinks);
ListView listDrinks = (ListView) findViewById(R.id.list_drinks);
listDrinks.setAdapter(listAdapter);
 Java
ListView listDrinks = (ListView) findViewById(R.id.list_drinks);
listDrinks.setAdapter(listAdapter);
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> listDrinks,
View itemView,
int position,
long id) {
//Pass the drink the user clicks on to DrinkActivity
Intent intent = new Intent(DrinkCategoryActivity.this,
DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) id);
startActivity(intent);
}
};
//Assign the listener to the list view
listDrinks.setOnItemClickListener(itemClickListener);
Drink Detail Activity <LinearLayout
 Xml android:orientation=“vertical”>

<ImageView
android:id="@+id/photo"
android:layout_width="190dp"
android:layout_height="190dp" />

<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Cont’d public static final String EXTRA_DRINKID = "drinkId";
int drinkId = (Integer)getIntent().getExtras().get(EXTRA_DRINKID);
 Java Drink drink = Drink.drinks[drinkId];

//Populate the drink name


TextView name = (TextView)findViewById(R.id.name);
name.setText(drink.getName());
//Populate the drink description
TextView description = (TextView)findViewById(R.id.description);
description.setText(drink.getDescription());
//Populate the drink image
ImageView photo = (ImageView)findViewById(R.id.photo);
photo.setImageResource(drink.getImageResourceId());
photo.setContentDescription(drink.getName());
Dialogs
 Is small window that prompts the user to make a decision or
enter additional information's.
 Dialog boxes in Android are partially transparent, floating
Activities or Fragments that partially obscure the user interface
 A dialog doesn’t fill the screen and is normally used for modal
events that require users to take an action before they can
procced.
Why Dialogs
 Dialogs can be used in different ways
 Can be used to help users answers some questions
 To make Selection
 Display warning or error messages
 Confirm Actions
Types of Dialog
 The Dialog class is the base class for dialogs but we have to
instantiate the subclasses of Dialog rather than using directly.
 In android the most commonly used types of dialogs are
 Alert Dialog
 Progress Dialog (Progress Bar)
 Date and Time Picker
 Custom Dialog
 Alert Dialog: shows alert messages and gives the answer in the form
of yes or no. According to our response the next step is processed.
Cont’d[Alert Dialog]
 Android Alert Dialog is built with three fields:
 Title
 Message(Content) Area
 Action Button
 Title: This is optional and should be used only when the content area is
occupied by a detailed message , a list or custom layout.
We use setTitle() method for displaying Alet Dialog box Title, setIcon() is used to
set the icon before the title.
 Message(Content) Area: this can display a message, a list, or other custom
layout.
We use setMessage() method for displaying the message
 Action Button: There should be no more than three action buttons in a
dialog.
Cont’d
 Positive: used to accept and continue with the action(the “Ok” or
“Yes” action)
 Negative: used to cancel the action(“No” action)
 Neutral: used when the user may not want to proceed with the
action, but doesn't necessarily want to cancel (“Remind Me Later”
action)
 We can add a list in Alert Dialog
 A traditional single-choice list
 A single-choice list (radio buttons)
 A multiple-choice list (checkboxes
 setItems() method can be used to add our list items.
 setSingleChoiceItems() used to create a list of Radio Buttons
 setMultipleChoiceItems() used to create a list of Check Boxes.
Example
 Try to develop this dialog when a button is pressed.

Are you want to exit?

Yes No
Cont’d AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Alert")
.setMessage("Are you sure, you want to exit ?")
 Java Code .setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
//Creating dialog box
AlertDialog dialog = builder.create();
dialog.show();
}
});
 Progress Dialog: is used to display the status of work being done like
analyzing status of work or downloading a file.
 By default the Progress Bar will be displayed as a Spinning wheel, if
we want to display it in a horizontal bar we have to change the style
property to horizontal like
style="?android:attr/progressBarStyleHorizontal".
 Progress bar supports two type of modes to show the progress.
 Determinate

 Indeterminate

 Determinate: progress mode is used in progress bar when we want


to show the quantity of progress has occurred. For example, the
percentage of file downloaded or percent remaining of an audio
file that is playing.
Cont’d
 To use Determinate progress, we need to set the style of the progress bar
to progressBarStyleHorizontal and set the amount of progress
using android:progress attribute.
 Indeterminate: progress mode is used in progress bar when we don’t know
how long an operation will take or how much work has done.
In indeterminate mode the actual progress will not be shown, only the cyclic
animation will be shown to indicate that some progress is happing.
 Progress Bar is different from Progress Dialog
 Progress
Bar is a View, which can be used in the layout to
show some progress while the user may still interact with other
parts
 Progress Dialog is a Dialog with builtin Progress Bar
(depreciated in Api 26). It is used when we want to prevent
the user from interacting with the application. The Dialog
freezes the user from doing anything until it is dismissed
Indeterminate Mode
Using Progress Dialog
ProgressDialog loading;
loading= ProgressDialog(context,title,message,indeteminate(boolean), cancelable);

Using Progress Bar


<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:layout_centerHorizontal="true"/>

In our Activity
final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton = (Button) findViewById(R.id.startButton);
// perform click event on button
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// visible the progress bar
Determinate Mode
progressDialog = new ProgressDialog(MainActivity.this);
 progressDialog.setMax(100); // Progress Dialog Max Value
progressDialog.setMessage("Loading..."); // Setting Message
progressDialog.setTitle("ProgressDialog"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // Progress Dialog Style Horizontal
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
@Override
public void run() {
try {
while (progressDialog.getProgress() <= progressDialog.getMax()) {
Thread.sleep(200);
progressDialog.incrementProgressBy(2);
if (progressDialog.getProgress() == progressDialog.getMax()) {
progressDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
});
 Date and Timer Picker Dialog: A dialog that is used to select date
and time.
 Custom Dialog: To create a Custom Dialog we need to create a
Custom Layout for the Dialog window with Layout and Widget
elements.
 We set the custom layout as the dialog content view

Context mContext = getApplicationContext();


Dialog dialog = new Dialog(mContext);

dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");

TextView text = (TextView) dialog.findViewById(R.id.text);


text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
Fragment
 Assume you want your app to behave differently depending on
whether it’s running on a phone or a tablet? In such cases you need
Fragments.
 The aim of Fragment is to create modular code in our Application.
 The code can be reused by different activities.
 Fragments have their own lifecycle and layouts or UI components
 A Fragment is a class that contains a portion of an application’s user
interface, which can be added as part of an app UI.
 Fragments also have their logic and can thus, accept and handle
different events.
E.g. The standard date picker is a Fragment—an instance of Dialog
Fragment, a subclass of Fragment—that enables the user to input a date.
The standard date picker shows a dialog window floating on top of the
Activity window.
Example
Cont’d[Example]

Activity vs Fragment
Activity Fragment
Activity is an application component that The fragment is only part of an activity, it
gives a user interface where the user can basically contributes its UI to that activity.
interact.

Fragment is dependent on activity. It


Activity is not dependent on fragment can’t exist independently.

we need to mention all activity it in the Fragment is not required to mention in the
manifest.xml file manifest file

Activity is not light weight. The fragment is the light weight.


We can’t create multi-screen UI without After using multiple fragments in a single
using fragment in an activity. activity, we can create a multi-screen UI.
Features of Fragments
 Before fragments we can show a single Activity on the screen at once.
But with the help of fragments we can divide the screen and controls
different parts separately.
 Reuse a Fragment. We can write the Fragment code once, and reuse
the Fragment in more than one Activity without having to repeat code.
 Add or remove a Fragment dynamically. Add, replace, or remove a
Fragment from An activity as needed.
 Integrate a mini-UI within the Activity. Integrate a Fragment with an
Activity UI or overlay the UI, so that the user can interact with the
Fragment UI without leaving the Activity.
 Retain data instances after a configuration change. Since a Fragment
has its own lifecycle, it can retain an instance of its data after a
configuration change (such as changing the device orientation).
 Represent sections of a layout for different screen sizes. Encapsulating
an interactive UI within a Fragment makes it easier to display the
interactive UI on different screen sizes.
Fragment Life Cycle
Cont’d
 N.B. A Fragment lifecycle is very similar to an Activity life cycle’s., ,
but it has a few extra steps. This is because it needs to interact with
the lifecycle of the activity that contains it.
 As with an Activity, you can save the variable assignments in a
Fragment.
 onCreateView(): The onCreateView() method returns a View object
that represents the fragment’s user interface. It gets called when
Android is ready to instantiate the user interface, and it takes three
parameters:
1) Layout inflator: used for inflating the fragment layout. Inflating the
layout turns your XML views into Java Objects.
2) View Group: This is the View Group in the activity’s layout that will
contain the fragment.
3) Bundle: . This is used if you’ve previously saved the fragment’s state,
and want to reinstate it.
 Use Activity context on Fragment
 The Activity context is used by a fragment to get a reference to its
hosting Activity.
 getActivity() is used to achieve this task
View listView = getActivity().findViewById(R.id.list);
N.B. getActivity() when the Fragment is not attached to an Activity,
getActivity() returns null.
 Use Fragment Methods in the host Activity
 your Activity can call methods in the Fragment by acquiring a reference
to the Fragment from FragmentManager or Support Fragment Manager,
using findFragmentById()
 ExampleFragment fragment = (ExampleFragment)
getFragmentManager().findFragmentById(R.id.example_fragment);
 Fragment to Fragment communication is handled through Activity
Fragment inherit lifecycle methods
 The fragment class doesn’t extend the Activity class.
 Some methods that are available to activities aren’t available to
fragments.
 Fragment class doesn’t implement the Context
Class. So, unlike an activity, a fragment isn’t a type
of context and therefore doesn’t have direct access
to global information about the application environment.
Instead, fragments must access this information using the
context of other objects such as its parent activity.
Exercise
 Create WorkoutDetail Fragment
 Create WorkoutList Fragment
 Coordinate the fragments to display the correct workout
 First we need to create Main Activity and Detail Activity
Main Activity is used for WorkoutList Fragement
Detail Activity is used for WorkoutDetail Fragment.
We start by working on the fragment for DetailActivity first, and adding
a button to MainActivity will give us an easy way of navigating from
MainActivity to DetailActivity.
 In your activity_main add button, in the activity code start Intent to
shift into Detail Activity
Workout Detail Fragment
 In Your Package name, New...→Fragment→Fragment (Blank).

<LinearLayout

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/workout_title"
android:id="@+id/textTitle" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/workout_description"
android:id="@+id/textDescription" />
DetailActivity Layout
 layout file requires a single view or view group as its root element. If
your activity only contains a fragment, the fragment itself can be
the root element.

<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.hfad.workout.WorkoutDetailFragment“
android:id="@+id/detail_frag"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Workout class public class WorkoutDetailFragment extends F
{
private long workoutId;
(refer page no. 360) @Override
public View onCreateView(LayoutInflater in
 Fragments don’t include ViewGroup container,
a findViewById() method, for instance. Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_worko
To get a reference to a fragment’s views, container, false);
we first have to get a reference to the }
@Override
fragment’s root view using the getView() public void onStart() {
super.onStart();
method, and use that to find its child views.
View view = getView();
if (view != null) {
TextView title = (TextView)
view.findViewById(R.id.textTitle);
Workout workout = Workout.workouts[(int) wo
title.setText(workout.getName());
TextView description = (TextView)
view.findViewById(R.id.textDescription
description.setText(workout.getDescriptio
}
WorkList Fragment
 A list fragment is a fragment that contains only a list
 A list fragment is a type of fragment that specializes in working with
a list view. It has a default layout that contains the list view.
 Advantage of List Fragment
 You don’t to create your own Layout
 There is no XML layout needed. List Fragment define there own
layout programmatically.
 getListView() method is used to access the list view in your fragment
code
 You don’t have to implement your own event Listener
 List Fragment class automatically implements an event listener that
listens for when items in the list view are clicked. We just need to
implement onListItemClick() method.
Add data to ListView Fragment
 We want to supply the list view in WorkoutListFragment with an array
of workout names
 ArrayAdapter can be used to bind our workout names(array) in list
view.
 Unlike an Activity we cant use this to pass the current context to the
array adapter. Why?
 The solution is use another object getContext() method to get a
reference to the current context.
 If the adapter is created on the fragment’s onCreateView()
method, the getContext() method of the onCreateView()
LayoutInflator parameter can be used to get the context instead.
 The last step is to set adapter in the listview. We use setListAdapter()
method.
WorkListFragment
 public class WorkoutListFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
String[] names = new String[Workout.workouts.length];
for (int i = 0; i < names.length; i++) {
names[i] = Workout.workouts[i].getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(
inflater.getContext(), android.R.layout.simple_list_item_1,
names);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Main Activity Layout

<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.hfad.workout.WorkoutListFragment“
android:id="@+id/detail_frag"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Connect the list to detail
3 steps
 Add code to WorkoutListFragment that waits for a workout to be
clicked.
 When that code runs, call some code in MainActivity.java that will
start DetailActivity, passing it the Id of the Workout
 Get DetailActivity to pass the ID to WorkoutDetailFragment so that the
fragment can display details of the correct workout.
 By defining Interface in our work list fragment we can communicate
the work list with main activity with little effort as well we can reuse
code.
ListView Fragment
 Define the Listener interface
static interface Listener {
void itemClicked(long id);
};
 Register the listener: We need to save a reference to the activity
WorkoutListFragment.
private Listener listener;
public void onAttach(Context context) {
super.onAttach(context);
this.listener = (Listener)context;
}
Cont’d
 Respond to clicks: When an item in WorkoutListFragment gets
clicked, we want to call the listener’s itemClicked() method.
public void onListItemClick(ListView listView, View itemView, int position,
long id) {
if (listener != null) {
listener.itemClicked(id);
}
}
Main Activity
 Main Activity needs to implement the interface
public class MainActivity extends AppCompatActivity
implements WorkoutListFragment.Listener {
@Override
public void itemClicked(long id) {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra(“id”, (int)id);
startActivity(intent);
}

You might also like