SlideShare a Scribd company logo
1 of 18
Android App Development
Lesson 9 - ActionBar, Toasts, Notifications & Preferences
This Week
● The ActionBar
● Toasts
● Notifications - Notifcation Area and Notification
Drawer
● Preferences
The ActionBar
● As well as displaying the title we can add actions to the
ActionBar.
● A typical well known example would be actions on the
ActionBar of the Android GMail App.
Each action is typically
added to the ActionBar via a
menu resource XML file
within the menu directory of
your app resources.
The ActionBar
● The ActionBar is the part of at the top of an Activity
where we’ve already seen the title of the Activity
NOTE : ActionBar was introduced in
Android 3.0. Before that you needed to
use an additional library. This is why you
sometimes see appcompat.v7 alongside
your project. If you choose just to
support 3.0 and up (which is
reasonable) you won’t need that library.
Just import android.app.ActionBar
from 3.0 on.
Adding ActionBar Actions
● If like GMail we wanted to add two actions to the
ActionBar (e.g 1. Search & 2. Compose EMail) our XML would
look something like this…...
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"/>
<item android:id="@+id/action_compose"
android:icon="@drawable/ic_action_compose"
android:title="@string/action_compose" />
</menu>
Each item on the
action bar is
treated as a
menu item and
has the following
attributes
1. ID
2. Icon
3. Title
To display an icon (if possible)
use
android:showAsAction=”ifRoom”
ActionBar Java Code
● As similar to fragment XML files we need to “inflate”
the menu XML file within the lifecycle of the Activity.
● To do this we override the onCreateOptionsMenu
lifecycle method of Activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
This presumes our menu
resource file is called
mainmenu.xml
NOTE : If there are too
many actions the the
overflow button will
appear.
Reacting to ActionBar Click
● When an item on the ActionBar of an Activity then
the onOptionsItemSelected method of that Activity is
invoked. So we override that method…..
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search://Do the search
break;
case R.id.action_compose://Do the compose
break;
}
return true;
Remember these
were the IDs
defined in the
menu resource
XML file
Toasts
● A Toast in Android is used for very simple feedback
messages in a small (and usually short-lived) popup which
is just large enough to contain the text.
To create a Toast we call a static
method on the Toast class
Toast myToast =
Toast.makeText(...);
which takes the following
parameters
1. Application Context
Toasts
Context context = getApplicationContext();
CharSequence text = "Mail has been sent!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
By default a Toast will appear above the
bottom center of the Activity.
Notifications
● Most Android users rely heavily on the Notifications
area of their device => Consider using it in your app!
● Notifications in Android consists of two distinct areas
The Notification Area
The Notification
Drawer
What’s in a Notification ?
● A Notification object can has many different pieces of
information which can be set but MUST contain at least
the following…..
❏ A Small Icon (for the Notification Area) - setSmallIcon()
❏ A Title - setContentTitle()
❏ Detail Text - setContentText()
The following is also common but non-mandatory..
❏ An Intent to launch something if notification is
clicked- setContentIntent()
Creating a Notification
● Similar to an AlertDialog (previous lecture) we need a
Builder to create a Notification.
//Create the Builder
NotificationCompat.Builder myBuilder =new NotificationCompat.Builder(this)
//Set the values of the Notification
myBuilder.setSmallIcon(R.drawable.my_notification_icon);
myBuilder.setContentTitle(“You have a new message!”);
myBuilder.setContentText(“Hi, how are you ?”)
//”Build” the Notification object
Notification myNotification = myBuilder.build();
Triggering a Notification
● Once a notification is built, it needs to be triggered
using the NotificationManager object.
● NotificationManager is something which is already
instatiated and present in the Android Platform. We
access it as follows …….
NotificationManager nManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Triggering a Notification
● Once we have an instance of both a Notification object
and a NotificationManger we trigger the notification via
the notify() method of NotificationManger.
nManager.notify(0, myNotification);
The
NotificationManager
instance
The Notification
instance created
by the Builder.
This int is the Notification ID. It should
be unique for each notification within
your app. If you trigger another
Notification with the same ID it will
replace the original
Preferences
● In the vast majority of apps there will be a “Settings”
section (and the user will expect it of any decent app)
● In the last lecture we saw the “model” for storing
Preferences (i.e. SharedPreferences)
● Now we’ll focus on the “view” part of Preferences
which we will build by subclassing two Android UI
classes.
PreferenceActivity - For our preference Activity!
Preference - For each item in the Preference
Activity.
Preferences UI
● PreferenceActivity extends ListActivity (which we’ve
already mentioned) (Note : There’s also a PreferenceFragment)
● Preference already has a number of useful subclasses
defined (e.g. CheckBoxPreference, ListPreference &
EditTextPreference)
● As with any Android interface we have done thus far
we add our UI components via XML.
● For preferences it is /res/xml/preferences.xml
Preferences XML
● For the moment we’ll look at how we’d add a
CheckboxPreference
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pref_auto_refresh"
android:title="@string/pref_autorefresh"
android:summary="@string/pref_autorefresh_summary"
android:defaultValue="true" />
</PreferenceScreen>
● We must have a key and defaultValue which get stored in
SharedPreferences
Bringing it together
● Finally we create our Activity (or Fragment) and read
in the XML file.
public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
● This automatically creates a SharedPreferences and
saves the preferences there! (OK for basic preference storage)

More Related Content

What's hot

Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intentDiego Grancini
 
Android notification
Android notificationAndroid notification
Android notificationKrazy Koder
 
iRidium Script: Interfaces
iRidium Script: InterfacesiRidium Script: Interfaces
iRidium Script: InterfacesiRidiumMobile365
 
Observer pattern
Observer patternObserver pattern
Observer patternanshu_atri
 
Android: Intent, Intent Filter, Broadcast Receivers
Android: Intent, Intent Filter, Broadcast ReceiversAndroid: Intent, Intent Filter, Broadcast Receivers
Android: Intent, Intent Filter, Broadcast ReceiversCodeAndroid
 
Local Notification Tutorial
Local Notification TutorialLocal Notification Tutorial
Local Notification TutorialKetan Raval
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingPayal Dungarwal
 

What's hot (14)

Android App Development - 02 Activity and intent
Android App Development - 02 Activity and intentAndroid App Development - 02 Activity and intent
Android App Development - 02 Activity and intent
 
Android notification
Android notificationAndroid notification
Android notification
 
iRidium Script: Interfaces
iRidium Script: InterfacesiRidium Script: Interfaces
iRidium Script: Interfaces
 
Android - Android Intent Types
Android - Android Intent TypesAndroid - Android Intent Types
Android - Android Intent Types
 
Android development session 2 - intent and activity
Android development   session 2 - intent and activityAndroid development   session 2 - intent and activity
Android development session 2 - intent and activity
 
Android menus in android-chapter15
Android menus in android-chapter15Android menus in android-chapter15
Android menus in android-chapter15
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Exercises
ExercisesExercises
Exercises
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Android: Intent, Intent Filter, Broadcast Receivers
Android: Intent, Intent Filter, Broadcast ReceiversAndroid: Intent, Intent Filter, Broadcast Receivers
Android: Intent, Intent Filter, Broadcast Receivers
 
05 intent
05 intent05 intent
05 intent
 
Local Notification Tutorial
Local Notification TutorialLocal Notification Tutorial
Local Notification Tutorial
 
Android intent
Android intentAndroid intent
Android intent
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 

Viewers also liked

Crea con tus manos - Actividades Extraescolares 2013 2014
Crea con tus manos - Actividades Extraescolares 2013 2014Crea con tus manos - Actividades Extraescolares 2013 2014
Crea con tus manos - Actividades Extraescolares 2013 2014ColegioSanPedroySanFelices
 
Introduction & App Structure
Introduction & App StructureIntroduction & App Structure
Introduction & App StructureCITSimon
 
26 Amazing Content marketing Facts and Statistics 2015 Infographic
26 Amazing Content marketing Facts and Statistics 2015 Infographic26 Amazing Content marketing Facts and Statistics 2015 Infographic
26 Amazing Content marketing Facts and Statistics 2015 InfographicInfographics Designs Pro
 
Informe_Donaciones_11-12_ing_3
Informe_Donaciones_11-12_ing_3Informe_Donaciones_11-12_ing_3
Informe_Donaciones_11-12_ing_3Jorge Chial
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationCITSimon
 

Viewers also liked (12)

Crea con tus manos - Actividades Extraescolares 2013 2014
Crea con tus manos - Actividades Extraescolares 2013 2014Crea con tus manos - Actividades Extraescolares 2013 2014
Crea con tus manos - Actividades Extraescolares 2013 2014
 
Introduction & App Structure
Introduction & App StructureIntroduction & App Structure
Introduction & App Structure
 
26 Amazing Content marketing Facts and Statistics 2015 Infographic
26 Amazing Content marketing Facts and Statistics 2015 Infographic26 Amazing Content marketing Facts and Statistics 2015 Infographic
26 Amazing Content marketing Facts and Statistics 2015 Infographic
 
A small trip to bluff
A small trip to bluffA small trip to bluff
A small trip to bluff
 
da Guiné ao Brasil
da Guiné ao Brasilda Guiné ao Brasil
da Guiné ao Brasil
 
Lesson 10
Lesson 10Lesson 10
Lesson 10
 
Essays to tariq's articles
Essays to tariq's articlesEssays to tariq's articles
Essays to tariq's articles
 
Lesson 3
Lesson 3Lesson 3
Lesson 3
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
 
Informe_Donaciones_11-12_ing_3
Informe_Donaciones_11-12_ing_3Informe_Donaciones_11-12_ing_3
Informe_Donaciones_11-12_ing_3
 
Spss
SpssSpss
Spss
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment Communication
 

Similar to Lesson 9

Android Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompatAndroid Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompatcbeyls
 
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.pptMD-IV-CH-ppt.ppt
MD-IV-CH-ppt.pptbharatt7
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycleKumar
 
Data Transfer between activities and Database
Data Transfer between activities and Database Data Transfer between activities and Database
Data Transfer between activities and Database faiz324545
 
Chapt 04 user interaction
Chapt 04 user interactionChapt 04 user interaction
Chapt 04 user interactionEdi Faizal
 
Unit 5 Activity and Activity Life Cycle.pptx
Unit 5 Activity and Activity Life Cycle.pptxUnit 5 Activity and Activity Life Cycle.pptx
Unit 5 Activity and Activity Life Cycle.pptxShantanuDharekar
 
Android Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intentsAndroid Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intentsDenis Minja
 
Android webinar class_3
Android webinar class_3Android webinar class_3
Android webinar class_3Edureka!
 
Android Application Components-BroadcastReceiver_Content Provider.pptx
Android Application Components-BroadcastReceiver_Content Provider.pptxAndroid Application Components-BroadcastReceiver_Content Provider.pptx
Android Application Components-BroadcastReceiver_Content Provider.pptxKNANTHINIMCA
 
Lecture #3 activities and intents
Lecture #3  activities and intentsLecture #3  activities and intents
Lecture #3 activities and intentsVitali Pekelis
 
Chapter 2 lesson-1 adding the action bar
Chapter 2 lesson-1 adding the action barChapter 2 lesson-1 adding the action bar
Chapter 2 lesson-1 adding the action barKalluri Vinay Reddy
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android DevelopmentAly Abdelkareem
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart JfokusLars Vogel
 
XMetaL Dialog Odds & Ends
XMetaL Dialog Odds & EndsXMetaL Dialog Odds & Ends
XMetaL Dialog Odds & EndsXMetaL
 

Similar to Lesson 9 (20)

Activity & Shared Preference
Activity & Shared PreferenceActivity & Shared Preference
Activity & Shared Preference
 
Android Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompatAndroid Support Library: Using ActionBarCompat
Android Support Library: Using ActionBarCompat
 
Android action bar and notifications-chapter16
Android action bar and notifications-chapter16Android action bar and notifications-chapter16
Android action bar and notifications-chapter16
 
Android
AndroidAndroid
Android
 
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.pptMD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
 
unit3.pptx
unit3.pptxunit3.pptx
unit3.pptx
 
Android lifecycle
Android lifecycleAndroid lifecycle
Android lifecycle
 
Data Transfer between activities and Database
Data Transfer between activities and Database Data Transfer between activities and Database
Data Transfer between activities and Database
 
Chapt 04 user interaction
Chapt 04 user interactionChapt 04 user interaction
Chapt 04 user interaction
 
Unit 5 Activity and Activity Life Cycle.pptx
Unit 5 Activity and Activity Life Cycle.pptxUnit 5 Activity and Activity Life Cycle.pptx
Unit 5 Activity and Activity Life Cycle.pptx
 
Android Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intentsAndroid Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intents
 
Android webinar class_3
Android webinar class_3Android webinar class_3
Android webinar class_3
 
Android Application Components-BroadcastReceiver_Content Provider.pptx
Android Application Components-BroadcastReceiver_Content Provider.pptxAndroid Application Components-BroadcastReceiver_Content Provider.pptx
Android Application Components-BroadcastReceiver_Content Provider.pptx
 
Lecture #3 activities and intents
Lecture #3  activities and intentsLecture #3  activities and intents
Lecture #3 activities and intents
 
Chapter 2 lesson-1 adding the action bar
Chapter 2 lesson-1 adding the action barChapter 2 lesson-1 adding the action bar
Chapter 2 lesson-1 adding the action bar
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
Lab3-Android
Lab3-AndroidLab3-Android
Lab3-Android
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
 
XMetaL Dialog Odds & Ends
XMetaL Dialog Odds & EndsXMetaL Dialog Odds & Ends
XMetaL Dialog Odds & Ends
 
Android 3
Android 3Android 3
Android 3
 

Lesson 9

  • 1. Android App Development Lesson 9 - ActionBar, Toasts, Notifications & Preferences
  • 2. This Week ● The ActionBar ● Toasts ● Notifications - Notifcation Area and Notification Drawer ● Preferences
  • 3. The ActionBar ● As well as displaying the title we can add actions to the ActionBar. ● A typical well known example would be actions on the ActionBar of the Android GMail App. Each action is typically added to the ActionBar via a menu resource XML file within the menu directory of your app resources.
  • 4. The ActionBar ● The ActionBar is the part of at the top of an Activity where we’ve already seen the title of the Activity NOTE : ActionBar was introduced in Android 3.0. Before that you needed to use an additional library. This is why you sometimes see appcompat.v7 alongside your project. If you choose just to support 3.0 and up (which is reasonable) you won’t need that library. Just import android.app.ActionBar from 3.0 on.
  • 5. Adding ActionBar Actions ● If like GMail we wanted to add two actions to the ActionBar (e.g 1. Search & 2. Compose EMail) our XML would look something like this…... <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_search" android:icon="@drawable/ic_action_search" android:title="@string/action_search"/> <item android:id="@+id/action_compose" android:icon="@drawable/ic_action_compose" android:title="@string/action_compose" /> </menu> Each item on the action bar is treated as a menu item and has the following attributes 1. ID 2. Icon 3. Title To display an icon (if possible) use android:showAsAction=”ifRoom”
  • 6. ActionBar Java Code ● As similar to fragment XML files we need to “inflate” the menu XML file within the lifecycle of the Activity. ● To do this we override the onCreateOptionsMenu lifecycle method of Activity @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return true; } This presumes our menu resource file is called mainmenu.xml NOTE : If there are too many actions the the overflow button will appear.
  • 7. Reacting to ActionBar Click ● When an item on the ActionBar of an Activity then the onOptionsItemSelected method of that Activity is invoked. So we override that method….. @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search://Do the search break; case R.id.action_compose://Do the compose break; } return true; Remember these were the IDs defined in the menu resource XML file
  • 8. Toasts ● A Toast in Android is used for very simple feedback messages in a small (and usually short-lived) popup which is just large enough to contain the text. To create a Toast we call a static method on the Toast class Toast myToast = Toast.makeText(...); which takes the following parameters 1. Application Context
  • 9. Toasts Context context = getApplicationContext(); CharSequence text = "Mail has been sent!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); By default a Toast will appear above the bottom center of the Activity.
  • 10. Notifications ● Most Android users rely heavily on the Notifications area of their device => Consider using it in your app! ● Notifications in Android consists of two distinct areas The Notification Area The Notification Drawer
  • 11. What’s in a Notification ? ● A Notification object can has many different pieces of information which can be set but MUST contain at least the following….. ❏ A Small Icon (for the Notification Area) - setSmallIcon() ❏ A Title - setContentTitle() ❏ Detail Text - setContentText() The following is also common but non-mandatory.. ❏ An Intent to launch something if notification is clicked- setContentIntent()
  • 12. Creating a Notification ● Similar to an AlertDialog (previous lecture) we need a Builder to create a Notification. //Create the Builder NotificationCompat.Builder myBuilder =new NotificationCompat.Builder(this) //Set the values of the Notification myBuilder.setSmallIcon(R.drawable.my_notification_icon); myBuilder.setContentTitle(“You have a new message!”); myBuilder.setContentText(“Hi, how are you ?”) //”Build” the Notification object Notification myNotification = myBuilder.build();
  • 13. Triggering a Notification ● Once a notification is built, it needs to be triggered using the NotificationManager object. ● NotificationManager is something which is already instatiated and present in the Android Platform. We access it as follows ……. NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  • 14. Triggering a Notification ● Once we have an instance of both a Notification object and a NotificationManger we trigger the notification via the notify() method of NotificationManger. nManager.notify(0, myNotification); The NotificationManager instance The Notification instance created by the Builder. This int is the Notification ID. It should be unique for each notification within your app. If you trigger another Notification with the same ID it will replace the original
  • 15. Preferences ● In the vast majority of apps there will be a “Settings” section (and the user will expect it of any decent app) ● In the last lecture we saw the “model” for storing Preferences (i.e. SharedPreferences) ● Now we’ll focus on the “view” part of Preferences which we will build by subclassing two Android UI classes. PreferenceActivity - For our preference Activity! Preference - For each item in the Preference Activity.
  • 16. Preferences UI ● PreferenceActivity extends ListActivity (which we’ve already mentioned) (Note : There’s also a PreferenceFragment) ● Preference already has a number of useful subclasses defined (e.g. CheckBoxPreference, ListPreference & EditTextPreference) ● As with any Android interface we have done thus far we add our UI components via XML. ● For preferences it is /res/xml/preferences.xml
  • 17. Preferences XML ● For the moment we’ll look at how we’d add a CheckboxPreference <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <CheckBoxPreference android:key="pref_auto_refresh" android:title="@string/pref_autorefresh" android:summary="@string/pref_autorefresh_summary" android:defaultValue="true" /> </PreferenceScreen> ● We must have a key and defaultValue which get stored in SharedPreferences
  • 18. Bringing it together ● Finally we create our Activity (or Fragment) and read in the XML file. public class SettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } ● This automatically creates a SharedPreferences and saves the preferences there! (OK for basic preference storage)