Mobile Programming Lecture 7 Dialogs, Menus, and SharedPreferences.

Slides:



Advertisements
Similar presentations
CE881: Mobile and Social Application Programming Simon M. Lucas Menus and Dialogs.
Advertisements

All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
Hello world Follow steps under the sections “Create an AVD” and “Create a New Android Project” at
User Interface Classes.  Design Principles  Views & Layouts  Event Handling  Menus  Dialogs.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
@2011 Mihail L. Sichitiu1 Android Introduction Hello Views Part 1.
Cosc 4730 Android TabActivity and ListView. TabActivity A TabActivity allows for multiple “tabs”. – Each Tab is it’s own activity and the “root” activity.
Android Development (Basics)
Data Storage: Part 1 (Preferences)
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
PROG Mobile Java Application Development PROG Mobile Java Application Development Event Handling Creating Menus.
ANDROID UI – FRAGMENTS. Fragment  An activity is a container for views  When you have a larger screen device than a phone –like a tablet it can look.
Mobile Programming Lecture 2 Layouts, Widgets, Toasts, and Event Handling.
Favorite Twitter® Searches App Android How to Program © by Pearson Education, Inc. All Rights Reserved.
Hello world Follow steps under the sections “Create an AVD” and “Create a New Android Project” at
PMS /134/182 HEX 0886B6 PMS /39/80 HEX 5E2750 PMS /168/180 HEX 00A8B4 PMS /190/40 HEX 66CC33 By Adrian Gardener Date 9 July 2012.
Mobile Programming Lecture 6
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
@2011 Mihail L. Sichitiu1 Android Introduction GUI Menu Many thanks to Jun Bum Lim for his help with this tutorial.
Mobile Computing Lecture#11 Adapters and Dialogs.
Create Navigation Drawer Team 2 Zhong Wang Jiaming Dong Philip Wu Lingduo Kong.
Programming Mobile Applications with Android September, Albacete, Spain Jesus Martínez-Gómez.
Android – Fragments L. Grewe.
Cosc 5/4730 Dialogs and below 3.0 and above (fragment)
Cosc 4730 Android Fragments. Fragments You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own.
Copyright© Jeffrey Jongko, Ateneo de Manila University Editing ListAdapter Data part 2.
Copyright © Curt Hill More Components Varying the input of Dev-C++ Windows Programs.
Android Using Menus Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright © CommonsWare, LLC. ISBN:
Mobile Programming Midterm Review
Mobile Programming Lecture 3 Debugging. Lecture 2 Review What widget would you use to allow the user to enter o a yes/no value o a range of values from.
Mobile Programming Lecture 11 Animation and TraceView.
Styles, Dialog Boxes, and Menus. Styles Allow creation of a common format – placed in res/values/styles.xml – file name is incidental Can be applied.
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
Copyright© Jeffrey Jongko, Ateneo de Manila University Deconstructing HelloWorld.
ListView and ExpandableListView
Android: “Dynamic” data and Preferences data.
Android Application Lifecycle and Menus
Designing user interfaces using: Simple views 1. Views Basic views – TextView – EditText – Button – ImageButton – CheckBox – ToggleButton – RadioButton.
User Interface Layout Interaction. EventsEvent Handlers/Listeners Interacting with a user.
Android Alert Dialog. Alert Dialog Place Button to open the dialog. public class MainActivity extends ActionBarActivity { private static Button button_sbm;
Events. Slide 2©SoftMoore Consulting Events Events are generated when a user interacts with the view objects of an application. Examples –button clicked–
Mobile Programming Lecture 4 Resources, Selection, Activities, Intents.
ANDROID LAYOUTS AND WIDGETS. Slide 2 Introduction Parts of the Android screen Sizing widgets and fonts Layouts and their characteristics Buttons, checkboxes.
School of Engineering and Information and Communication Technology KIT305/KIT607 Mobile Application Development Android OS –Permissions (cont.), Fragments,
Mobile Application Development Data Storage. Android provides several options for you to save persistent application data. The solution you choose depends.
Java for android Development Nasrullah Khan. Using instanceof in Android Development the classes such as Button, TextView, and CheckBox, which represent.
The Flag Quiz app tests your ability to correctly identify 10 flags from various countries and territories.
Cosc 5/4730 Support design library. Support Design library Adds (API 9+) back support to a number of 5.0 lollipop widgets and material design pieces –
Editing a Twitter search. Viewing search results in a browser.
Fragments and Menus Chapter 4 1. Objectives Learn three different types of menus: options, context, and popup Learn to configure the ActionBar and Toolbar.
Menus. Menus are a common user interface component in many types of applications. The options menu is the primary collection of menu items for an activity.
Lab7 – Appendix.
Introduction to android
Android Programming - Features
CS499 – Mobile Application Development
CS240: Advanced Programming Concepts
GUI Programming Fundamentals
Android – Event Handling
Mobile Application Development Chapter 4 [Android Navigation and Interface Design] IT448-Fall 2017 IT448- Fall2017.
Android 15: Settings Kirk Scott.
ANDROID UI – FRAGMENTS UNIT II.
Mobile Computing With Android ACST 4550 Alerts
Android: Preferences and user settings data
Android Developer Fundamentals V2
Android Developer Fundamentals V2 Lesson 4
Objects First with Java
Mobile Programmming Dr. Mohsin Ali Memon.
Activities and Fragments
Implication of Orientation Changes
Preference Activity class
Presentation transcript:

Mobile Programming Lecture 7 Dialogs, Menus, and SharedPreferences

Agenda Dialogs Menus SharedPreferences

Android Application Components 1. Activity 2. Broadcast Receiver 3. Content Provider 4. Service

Dialogs A dialog is a small window that appears in front of the current Activity It causes the Activity to lose focus Used for ProgressBars, Alerts, etc

Dialogs onCreateDialog() is called the first time. onPrepareDialog is called every time its opened. o without this, it will remain the same as the first time it was opened

Dialogs - AlertDialog an AlertDialog is an extension of the Dialog class it is capable of constructing most dialog user interfaces and is the suggested dialog type

Dialogs - AlertDialog you should use it for dialogs that use any of the following features o a title o a text message o one, two, or three buttons o a list of selectable items (with optional checkboxes or radio buttons)

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; }

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } Nothing special here, just an int I use to identify the dialog, because we can have more than one

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } Override this method of Activity, which is called when you want to show any dialog of the Activity

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } Switch because we can have more than one dialog, meaning we need to check the dialog id

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } If you want an AlertDialog, you need to build one first

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } Give the user a message

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } If true, then the user can press the back button to dismiss the dialog. false would force the user to make an action on the dialog.

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } Add a button, AND set a listener for when the button is pressed. This is should be the "positive" button, e.g. "Yes", "Absolutely!"

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } This is the listener for then the "positive" button is pressed, so you should take some kind of action.

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } The Dialog isn't created until you call create()

Dialogs - Creating an AlertDialog public class MyDialogs extends Activity { static final int DIALOG_EXIT_ID = protected Dialog onCreateDialog(int id) { Dialog dialog = null; switch(id) { case DIALOG_EXIT_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to exit?"); builder.setCancelable(true); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AlertDialogExample.this.finish(); } }); dialog = builder.create(); break; } return dialog; } The type of this method is Dialog, so here we return... the Dialog!

Dialogs - AlertDialog You can add up to 3 buttons on the AlertDialog by calling 1.dialog.setPositiveButton() o we just used this one in the previous slides 2.dialog.setNegativeButton() o "No", "Cancel" 3.dialog.setNeutralButton() o "Remind me Later"

Dialogs - Showing a Dialog To show a Dialog on the screen, simply call o showDialog(int) from within your Activity. It takes as parameter the ID of the dialog. You can also call it from within an anonymous inner class Make sure you override the onCreateDialog() method in that Activity!

Dialogs - Showing a Dialog See AlertDialogExampleAlertDialogExample

Dialogs - Dismissing a Dialog You don't want to show the Dialog to the user forever! You have to allow the user to close the dialog somehow, even if it's not cancelable You can dismiss the Dialog by calling o dismissDialog(int) from within the controlling Activity where the argument is the Dialog ID o dismiss() on the Dialog object  e.g. dialog.dismiss()

Dialogs - Showing a Dialog See DismissDialogExampleDismissDialogExample

Dialogs - AlertDialog with a List Not only buttons! You can also add a list to your AlertDialog

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); }

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); } We will use this String array for our list

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); } This is a method in an Activity class, as in the previous example

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); } We're still using an AlertDialog Builder

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); } This time we call setItems()!

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); } First argument should be your list of items

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); } There is more than one OnClickListener class!

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); } If you want to use both View.OnclickListener (for buttons) and DialogInterface.OnClickListener (for Dialogs), then you need to be more specific here

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); } When an item in the list is clicked, Android kindly provides you with the Dialog object itself, as well as the index of the clicked item

Dialogs - AlertDialog with a List String[] countries = new String[]{"Netherlands", "USA", "St. Martin", public Dialog onCreateDialog(int id) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Country"); builder.setItems(countries, new DialogInterface.OnClickListener() public void onClick(DialogInterface dialog, int index) { Toast.makeText(getApplicationContext(), "You selected " + countries[index], Toast.LENGTH_LONG).show();} }); return builder.create(); } Let's not forget to create the Dialog and return it

Dialogs - AlertDialog with a List See AlertDialogListExampleAlertDialogListExample

Dialogs - Date/TimePicker Dialogs See DatePickerDialogExampleDatePickerDialogExample

Dialogs - Custom Dialogs - SeekBar You can create your own Dialog if the standard Android Dialogs are not suitable for your needs For example, there is no SeekBar Dialog, but you can create your own See CustomDialogExampleCustomDialogExample

Dialogs - DialogFragment creating Dialogs by using the onCreateDialog() method of an Activity is old school creating Dialogs by using a DialogFragment is new school

Dialogs - DialogFragment DialogFragment also has an onCreateDialog() callback method! o i.e., both an Activity and a DialogFragment have an onCreateDialog() callback method

Dialogs - DialogFragment DialogFragment is slightly different than the other Fragments we've seen so far We don't need to add it to the XML Nor do we need to add it to the UI using a FragmentTransaction

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); }

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); } Let's create our Activity first...

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); } Let's show the Dialog when this Button is clicked!

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); } The Button was just clicked at this point, so let's create a new instance of MyDialogFragment, which we will see in a few slides

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); } Just call.show() on the Fragment! This time we didn't need to use the FragmentTransaction to add the Fragment

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); } Just pass the FragmentManager and it will take care of adding and removing the Fragment for you

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); } Second argument is the tag that you want to assign to the Fragment

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); } We will get back to this!

Dialogs - DialogFragment Let's take a look at our DialogFragment

Dialogs - DialogFragment public class MyDialogFragment extends DialogFragment public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("This is a DialogFragment!"); builder.setPositiveButton("OK", new OnClickListener() public void onClick(DialogInterface dialog, int which) { MyActivity act= (MyActivity) getActivity(); act.doPositiveClick(); } }); return builder.create(); }

Dialogs - DialogFragment public class MyDialogFragment extends DialogFragment public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("This is a DialogFragment!"); builder.setPositiveButton("OK", new OnClickListener() public void onClick(DialogInterface dialog, int which) { MyActivity act= (MyActivity) getActivity(); act.doPositiveClick(); } }); return builder.create(); } DialogFragment!

Dialogs - DialogFragment public class MyDialogFragment extends DialogFragment public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("This is a DialogFragment!"); builder.setPositiveButton("OK", new OnClickListener() public void onClick(DialogInterface dialog, int which) { MyActivity act= (MyActivity) getActivity(); act.doPositiveClick(); } }); return builder.create(); } Dialog also has an onCreateDialog(), the proof is in

Dialogs - DialogFragment public class MyDialogFragment extends DialogFragment public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("This is a DialogFragment!"); builder.setPositiveButton("OK", new OnClickListener() public void onClick(DialogInterface dialog, int which) { MyActivity act= (MyActivity) getActivity(); act.doPositiveClick(); } }); return builder.create(); } This is how we get the Context from within a Fragment, remember!?

Dialogs - DialogFragment public class MyDialogFragment extends DialogFragment public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("This is a DialogFragment!"); builder.setPositiveButton("OK", new OnClickListener() public void onClick(DialogInterface dialog, int which) { MyActivity act= (MyActivity) getActivity(); act.doPositiveClick(); } }); return builder.create(); } We need to return a Dialog!

Dialogs - DialogFragment public class MyDialogFragment extends DialogFragment public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("This is a DialogFragment!"); builder.setPositiveButton("OK", new OnClickListener() public void onClick(DialogInterface dialog, int which) { MyActivity act= (MyActivity) getActivity(); act.doPositiveClick(); } }); return builder.create(); } You've seen this other stuff before!

Dialogs - DialogFragment public class MyDialogFragment extends DialogFragment public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("This is a DialogFragment!"); builder.setPositiveButton("OK", new OnClickListener() public void onClick(DialogInterface dialog, int which) { MyActivity act= (MyActivity) getActivity(); act.doPositiveClick(); } }); return builder.create(); } The button in the Dialog has now been clicked! What do we do next?

Dialogs - DialogFragment public class MyDialogFragment extends DialogFragment public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("This is a DialogFragment!"); builder.setPositiveButton("OK", new OnClickListener() public void onClick(DialogInterface dialog, int which) { MyActivity act= (MyActivity) getActivity(); act.doPositiveClick(); } }); return builder.create(); } Let's get a handle on the Activity containing this Fragment

Dialogs - DialogFragment public class MyDialogFragment extends DialogFragment public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("This is a DialogFragment!"); builder.setPositiveButton("OK", new OnClickListener() public void onClick(DialogInterface dialog, int which) { MyActivity act= (MyActivity) getActivity(); act.doPositiveClick(); } }); return builder.create(); } Let's call our own custom method, doPositiveClick() on the Activity

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); } Which takes us back here, back to our Activity.

Dialogs - DialogFragment public class MyActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() public void onClick(View v) { MyDialogFragment f = new MyDialogFragment(); f.show(getFragmentManager(), "dialog"); } }); } public void doPositiveClick() { Toast.makeText(this, "doPositiveClick()", Toast.LENGTH_LONG).show(); } Simply make a Toast as evidence that we were successful

Dialogs - DialogFragment Note that we don't need to override onCreateView() or onActivityCreated() methods of a DialogFragment You may choose to override onCreateView() and return a View if you want to create some custom Dialog without using onCreateDialog() I'll leave it up to the Android developer's website to explain it if anyone is interested in doing soAndroid developer's website

Dialogs - DialogFragment See FragmentDialogExample

Menu Options In Android 2.3.x and below, clicking on the dedicated Menu button allows the user to reveal menu options In Android 3.0 and above, the options menu is presented by way of an action bar o the dedicated Menu button is deprecated and some devices just do not have one

Menu Options - Creating one <= 2.3.x Right click on your project > New > Other... Select Android XML File In the Resource Type drop down list, select Menu Enter a File name and click Finish Click Add... > Item Edit the id as appropriate, and enter the Title Repeat to add additional menu options

Menu Options - Creating one <= 2.3.x We will use this Menu XML file, main_menu.xml, for our example <item <item />

Menu Options - Creating one <= public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; }

Menu Options - Creating one <= public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } Override this Activity method

Menu Options - Creating one <= public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } Similar to a LayoutInflater, but for Menus instead

Menu Options - Creating one <= public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } Show the Menu now

Menu Options - Creating one <= public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } This is the Menu XML file that we created previously

Menu Options - Creating one <= public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } This is given as argument to onCreateOptionsMenu, so use it as argument to inflate the menu

Menu Options - Creating one <= public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } Return true if you want the menu to be displayed, false if you don't

Menu Options - Creating one <= 2.3.x This is enough for the Menu to be displayed on the screen when the user presses the Menu button If you want to take action after an option is selected, then you need to override the onOptionsItemSelected() method of Activity

Menu Options - Creating one <= public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.set_text: TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("First Option Selected!"); break; case R.id.close: Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show(); finish(); break; } return true; }

Menu Options - Creating one <= public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.set_text: TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("First Option Selected!"); break; case R.id.close: Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show(); finish(); break; } return true; } We override this method of Activity

Menu Options - Creating one <= public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.set_text: TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("First Option Selected!"); break; case R.id.close: Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show(); finish(); break; } return true; } Which menu item was selected?

Menu Options - Creating one <= public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.set_text: TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("First Option Selected!"); break; case R.id.close: Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show(); finish(); break; } return true; } Here we just changed the text of a TextView when the item R.id.set_text is selected

Menu Options - Creating one <= public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.set_text: TextView tv = (TextView) findViewById(R.id.textView1); tv.setText("First Option Selected!"); break; case R.id.close: Toast.makeText(this, "Goodbye!", Toast.LENGTH_LONG).show(); finish(); break; } return true; } Here we close our app when item R.id.close is selected

Menu Options - Creating one <= 2.3.x See MenuOptionsExampleMenuOptionsExample

Menu Options - Creating one <= 2.3.x You can change the menu options that show up at runtime

Menu Options - Creating one >= 3.0 For Android 3.0 and higher...

Context Menu A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content.floating menu You can provide a context menu for any view, but they are most often used for items in a o ListView ListView o other view collections in which the user can perform direct actions on each item.

Context Menu - Creating one When creating a Context Menu, you can create a Menu XML file in the same way you do for an Options Menu

Context Menu - Creating one We will use the following XML file for our example

Context Menu - Creating one We will use the following XML file for our example All of the callback methods in this example are declared within our ListActivity

Context Menu - Creating one As a reminder, a ListActivity extends Activity it already has a ListView, so you don't need to add one the the Layout XML file o you don't even need to use a Layout XML File o which means you don't need to call setContentView() You can get a handle on the ListView by simply calling getListView().

Context Menu - Creating one public class ContextMenuExample extends ListActivity { String[] entries = new public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setListAdapter(new ArrayAdapter (this, android.R.layout.simple_list_item_1, entries)); registerForContextMenu(getListView()); }...

Context Menu - Creating one public class ContextMenuExample extends ListActivity { String[] entries = new public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setListAdapter(new ArrayAdapter (this, android.R.layout.simple_list_item_1, entries)); registerForContextMenu(getListView()); }... We will use this String array to populate our List

Context Menu - Creating one public class ContextMenuExample extends ListActivity { String[] entries = new public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setListAdapter(new ArrayAdapter (this, android.R.layout.simple_list_item_1, entries)); registerForContextMenu(getListView()); }... Populate the ListView here

Context Menu - Creating one public class ContextMenuExample extends ListActivity { String[] entries = new public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setListAdapter(new ArrayAdapter (this, android.R.layout.simple_list_item_1, entries)); registerForContextMenu(getListView()); }... Register the ListView with a Context Menu, now the menu will show up when you long press on the ListView

Context Menu - Creating one public class ContextMenuExample extends ListActivity { String[] entries = new public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); }... onCreate() from previous slide is here

Context Menu - Creating one public class ContextMenuExample extends ListActivity { String[] entries = new public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); }... Override this method. It is called when the Context Menu for View v is being built

Context Menu - Creating one public class ContextMenuExample extends ListActivity { String[] entries = new public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); }... You've seen this before

Context Menu - Creating one public class ContextMenuExample extends ListActivity { String[] entries = new public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); }... onContextItemSelected() on the next slide goes here

Context Menu - Creating public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null); switch(item.getItemId()) { case R.id.edit_option: /* Edit option selected */ break; case R.id.share_option: /* Share option selected */ break; case R.id.delete_option: /* Edit option selected */ break; } return true; } Override this method of Activity

Context Menu - Creating public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null); switch(item.getItemId()) { case R.id.edit_option: /* Edit option selected */ break; case R.id.share_option: /* Share option selected */ break; case R.id.delete_option: /* Edit option selected */ break; } return true; } This Object has information about the Context Menu, NOT the item in the List

Context Menu - Creating public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null); switch(item.getItemId()) { case R.id.edit_option: /* Edit option selected */ break; case R.id.share_option: /* Share option selected */ break; case R.id.delete_option: /* Edit option selected */ break; } return true; } This Object will have information about the item pressed

Context Menu - Creating public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null); switch(item.getItemId()) { case R.id.edit_option: /* Edit option selected */ break; case R.id.share_option: /* Share option selected */ break; case R.id.delete_option: /* Edit option selected */ break; } return true; } We can get a handle on the item in the ListView by using info.position

Context Menu - Creating public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null); switch(item.getItemId()) { case R.id.edit_option: /* Edit option selected */ break; case R.id.share_option: /* Share option selected */ break; case R.id.delete_option: /* Edit option selected */ break; } return true; } info.position tells us which item was pressed, this is how we tell which Menu Item was pressed

Context Menu - Creating public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); TextView tv = (TextView) getListView().getAdapter().getView(info.position, null, null); switch(item.getItemId()) { case R.id.edit_option: /* Edit option selected */ break; case R.id.share_option: /* Share option selected */ break; case R.id.delete_option: /* Edit option selected */ break; } return true; } By combining info.position and item.getItemId(), we know the action needs to be performed on the item

Context Menu - Creating one See ContextMenuExampleContextMenuExample

Preferences - SharedPreferences SharedPreferences is 1 of the 5 methods for Data Storage in Android Internal and external storage, remote server, and local database. It stores primitive key-value pairs of primitive data types o boolean, int, float, long, String Data persists even if your app has been fully terminated SharedPreferences are only available to app that created them!

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); }

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } The desired name of your SharedPreferences file

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } You can get a SharedPreferences file by name by calling this method

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } The second argument is the modemode

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } If the SharedPreferences file doesn't exist at this point, it will be created for you

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } Try to get the boolean value "silentMode", "silentMode" is the key. You decide on the name of the key. "silentMode" is not a keyword here

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } If the key doesn't exist (could be because the file was just created in the previous line of code), then this will be the value returned

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } An imaginary method that you created to change the volume setting of the device to silent

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } We want data to persist even after the app has been terminated, so let's Override onStop()

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } Get a handle on our SharedPreferences again, which should have the "silentMode" value set at this point

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } If we want to modify the SharedPreferences, we need to use a SharedPreferences Editor

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } Let's set the value value of silentMode to the imaginary boolean value mSilentMode

Preferences - SharedPreferences public class SharedPrefsExample extends Activity { public static final String PREFS_NAME = protected void onCreate(Bundle state){ super.onCreate(state); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); editor.commit(); } Don't forget to save your changes to the file!

Preferences - SharedPreferences See SharedPrefsExampleSharedPrefsExample

Preferences - PreferenceActivity If you want to provide the user with a UI for changing preferences, you can use a PreferenceActivity in combination with SharedPreferences To create a PreferenceActivity, first create a Preference XML file

Preferences - PreferenceActivity File > New > Other > Android XML File Resource Type: Preference Enter the file name, e.g. preferences.xml Root Element: PreferenceScreen Click Add to add various types of Preferences o e.g. EditText Expand the Attributes on the right to edit the attributes for your preferences

Preferences - PreferenceActivity We will use this preferences.xml file for our example

Preferences - PreferenceActivity Creating a PreferenceActivity is easy!

Preferences - PreferenceActivity public class Preferences extends PreferenceActivity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); }

Preferences - PreferenceActivity public class Preferences extends PreferenceActivity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } Extend PreferenceActivity

Preferences - PreferenceActivity public class Preferences extends PreferenceActivity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } From the preferences.xml file we added previously

Preferences - PreferenceActivity In your main Activity, you can get the Preferences without specifying the name of the XML file

Preferences - PreferenceActivity public class MainActivity extends Activity { SharedPreferences public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String username = mPrefs.getString("username","None"); }

Preferences - PreferenceActivity public class MainActivity extends Activity { SharedPreferences public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String username = mPrefs.getString("username","None"); } This will allow you to access the preference settings, even if you have more than one preference XML file associated with a PreferenceActivity

Preferences - PreferenceActivity public class MainActivity extends Activity { SharedPreferences public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String username = mPrefs.getString("username","None"); } These preferences will automatically save when the user interacts with them!

Preferences - PreferenceActivity See PreferenceActivityExamplePreferenceActivityExample

Preferences - PreferenceActivity You can also add a Listener for when a Preference has been changed When a Preference is changed, you may need to update certain values tied to these Preferences

Preferences - PreferenceFragment Android 3.0 and higher PreferenceFragment

References The Busy Coder's Guide to Android Development - Mark Murphy The Busy Coder's Guide to Android Development - Mark Murphy Android Developers The Mobile Lab at Florida State University