You are on page 1of 13

UNIT V

Menus, Dialogs List, Location & Maps and Animation

5.1 Localization

An android application can run on many devices in many different regions. In


order to make your application more interactive, your application should
handle text,numbers,files e.t.c in ways appropriate to the locales where your
application will be used.
The way of changing string into different languages is called as localization

In this chapter we will explain , how you can localize your application
according to different regions e.t.c. We will localize the strings used in the
application, and in the same way other things can be localized.

Localizing Strings
In order to localize the strings used in your application , make a new folder
under res with name of values-local where local would be the replaced with
the region.

For example, in the case of italy, the values-it folder would be made under
res. It is shown in the image below −

Once that folder is made, copy the strings.xmlfrom default folder to the
folder you have created. And change its contents. For example, i have
changed the value of hello_world string.

Italy, res/values-it/strings.xml

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

<resources>

<string name="hello_world">Ciao mondo!</string>


</resources>

Spanish, res/values-it/strings.xml

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

<resources>

<string name="hello_world">Hola Mundo!</string>

</resources>

French, res/values-it/strings.xml

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

<resources>

<string name="hello_world">Bonjour le monde !</string>

</resources>

Apart from these languages, the region code of other languages have been
given in the table below −

Sr.No Language & code

Afrikanns
1
Code: af. Folder name: values-af

Arabic
2
Code: ar. Folder name: values-ar

Bengali
3
Code: bn. Folder name: values-bn

Czech
4
Code: cs. Folder name: values-cs

Chinese
5
Code: zh. Folder name: values-zh

German
6
Code: de. Folder name: values-de

7 French
Code: fr. Folder name: values-fr

Japanese
8
Code: ja. Folder name: values-ja

5.2 Options menu and Context menu

Option Menu - MENU button

The first step in hooking up your menus to an Activity is to create them (which is already shown
above). The 2nd step is to hook into the Activity’s menu creation methods to call your code,
which creates these menu items:

// Menu button - option menu

/** hook into menu button for activity */

@Override public boolean onCreateOptionsMenu(Menu menu) {

populateMenu(menu);

return super.onCreateOptionsMenu(menu);

/** when menu button option selected */

@Override public boolean onOptionsItemSelected(Menu.Item item) {

return applyMenuChoice(item) || super.onOptionsItemSelected(item);

Here are some notes on this code:

1. The menu is created by Android and passed to you; you have to add whatever menu items
you want to this object, you don’t actually create the Menu. This allows Android to populate
the Menu with system defined menu items (in case you call
super.onCreateOptionsMenu(menu) for the Option menu).

2. If you add more than 5 menu items to the given menu, then the 6th option won’t not be
displayed in the grid (like they are in the screenshot above). A “More” button will be shown
and when you select this a list view will be shown with all your menu items. In the grid
view, the accelerators are not shown. The grid view only takes up the bottom portion of the
Activity/screen. The list view takes up the full screen and shows the keyboard accelerators.

3. The code to respond to menu item selection is shown below (this is common to the Option
and Context menu).

Context Menu - Press and hold


The first step in hooking up your menus to an Activity is to create them (which is already shown
above). The 2nd step is to hook into the Activity’s menu creation methods to call your code,
which creates these menu items.

Here’s the code to bind the menu items to a ListView component, so when you press-and-hold
this component, it will pop up a context menu:

@Override protected void onCreate(Bundle bundle) {

// wire up the listview to have a press-hold/context menu

View listview = ...

listview.setOnPopulateContextMenuListener(this);

/** press-hold/context menu */

public void onPopulateContextMenu(ContextMenu menu,

View view,

Object o) {

populateMenu(menu);

/** when press-hold option ji selected */

@Override public boolean onContextItemSelected(Menu.Item item) {

return applyMenuChoice(item) || super.onContextItemSelected(item);

Here are some notes on this code:

1. Just like with the Option menu, the Menu object is pre-created for you and passed to you.

2. Unlike the Context menu example, you don’t override a method in your Activity class, you
have to call setOnPopulateContextMenuListener(…) on the component you want to bind the
context menu with.

3. This onPopulateContextMenu(…) method is called every time the user performs a press-
and-hold operation on the ListView. This isn’t just created once (like the Option menu).
https://developerlife.com/2008/07/16/option-and-context-menu/#option-menu---menu-button

5.3 Dialogs- Alert dialog


A Dialog is small window that prompts the user to a decision or enter additional
information.

Some times in your application, if you wanted to ask the user about taking a
decision between yes or no in response of any particular action taken by the
user, by remaining in the same activity and without changing the screen, you
can use Alert Dialog.

In order to make an alert dialog, you need to make an object of


AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given
below

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

Now you have to set the positive (yes) or negative (no) button using the
object of the AlertDialogBuilder class. Its syntax is

alertDialogBuilder.setPositiveButton(CharSequence text,

DialogInterface.OnClickListener listener)

alertDialogBuilder.setNegativeButton(CharSequence text,

DialogInterface.OnClickListener listener)

Apart from this , you can use other functions provided by the builder class to
customize the alert dialog. These are listed below

Sr.No Method type & description

setIcon(Drawable icon)
1
This method set the icon of the alert dialog box.

setCancelable(boolean cancel able)


2
This method sets the property that the dialog can be cancelled or not

setMessage(CharSequence message)
3
This method sets the message to be displayed in the alert dialog

setMultiChoiceItems(CharSequence[] items, boolean[]


checkedItems, DialogInterface.OnMultiChoiceClickListener
listener)
4
This method sets list of items to be displayed in the dialog as the content.
The selected option will be notified by the listener

setOnCancelListener(DialogInterface.OnCancelListener
5 onCancelListener)
This method Sets the callback that will be called if the dialog is cancelled.

setTitle(CharSequence title)
6
This method set the title to be appear in the dialog

After creating and setting the dialog builder , you will create an alert dialog
by calling the create() method of the builder class. Its syntax is

AlertDialog alertDialog = alertDialogBuilder.create();

alertDialog.show();

This will create the alert dialog and will show it on the screen.

Dialog fragment
Before enter into an example we should need to know dialog fragment.Dialog
fragment is a fragment which can show fragment in dialog box

public class DialogFragment extends DialogFragment

@Override

public Dialog onCreateDialog(Bundle savedInstanceState) {

// Use the Builder class for convenient dialog construction

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener()


{

public void onClick(DialogInterface dialog, int id) {

toast.makeText(this,"enter a text here",Toast.LENTH_SHORT).show();

})

.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

finish();

});

// Create the AlertDialog object and return it

return builder.create();

}
}

List dialog
It has used to show list of items in a dialog box.For suppose, user need to
select a list of items or else need to click a item from multiple list of items.At
this situation we can use list dialog.

public Dialog onCreateDialog(Bundle savedInstanceState) {

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle(Pick a Color)

.setItems(R.array.colors_array, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

// The 'which' argument contains the index position

// of the selected item

});

return builder.create();

Single-choice list dialog


It has used to add single choice list to Dialog box.We can check or uncheck
as per user choice.

public Dialog onCreateDialog(Bundle savedInstanceState) {

mSelectedItems = new ArrayList();

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle("This is list choice dialog box");

.setMultiChoiceItems(R.array.toppings, null,

new DialogInterface.OnMultiChoiceClickListener() {

@Override

public void onClick(DialogInterface dialog, int which, boolean isChecked) {

if (isChecked) {
// If the user checked the item, add it to the selected items

mSelectedItems.add(which);

else if (mSelectedItems.contains(which)) {

// Else, if the item is already in the array, remove it

mSelectedItems.remove(Integer.valueOf(which));

})

// Set the action buttons

.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int id) {

// User clicked OK, so save the mSelectedItems results somewhere

// or return them to the component that opened the dialog

...

})

.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int id) {

...

});

return builder.create();

https://www.tutorialspoint.com/android/android_alert_dialoges.htm
5.4 Custom dialog

5.5 Dialog as Activity

5.6 Using string arrays


String resources

A string resource provides text strings for your application with optional text styling and
formatting. There are three types of resources that can provide your application with strings:

String

XML resource that provides a single string.

String Array

XML resource that provides an array of strings.

Quantity Strings (Plurals)

XML resource that carries different strings for pluralization.

All strings are capable of applying some styling markup and formatting arguments. For
information about styling and formatting strings, see the section about Formatting and Styling.

String
A single string that can be referenced from the application or from other resource files (such as
an XML layout).

Note: A string is a simple resource that is referenced using the value provided in the name attribute (not the
name of the XML file). So, you can combine string resources with other simple resources in the one XML file,
under one <resources> element.

file location:

res/values/filename.xml
The filename is arbitrary. The <string> element's name is used as the resource ID.

compiled resource datatype:

Resource pointer to a String.

resource reference:

In Java: R.string.string_name
In XML:@string/string_name

syntax:

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


<resources>
<string
name="string_name"
>text_string</string>
</resources>

elements:

<resources>

Required. This must be the root node.

No attributes.
<string>

A string, which can include styling tags. Beware that you must escape apostrophes and
quotation marks. For more information about how to properly style and format your strings
see Formatting and Styling, below.

attributes:
name

String. A name for the string. This name is used as the resource ID.

String array
An array of strings that can be referenced from the application.

Note: A string array is a simple resource that is referenced using the value provided in the nameattribute (not
the name of the XML file). As such, you can combine string array resources with other simple resources in the
one XML file, under one <resources> element.

file location:

res/values/filename.xml
The filename is arbitrary. The <string-array> element's name is used as the resource ID.

compiled resource datatype:

Resource pointer to an array of Strings.

resource reference:

In Java: R.array.string_array_name

syntax:

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


<resources>
<string-array
name="string_array_name">
<item
>text_string</item>
</string-array>
</resources>

elements:

<resources>
Required. This must be the root node.

No attributes.
<string-array>

Defines an array of strings. Contains one or more <item> elements.

attributes:
name

String. A name for the array. This name is used as the resource ID to reference the array.

<item>

A string, which can include styling tags. The value can be a reference to another string resource.
Must be a child of a <string-array> element. Beware that you must escape apostrophes and
quotation marks. See Formatting and Styling, below, for information about to properly style and
format your strings.

No attributes.

https://developer.android.com/guide/topics/resources/string-resource

5.7 Creating lists, and Custom lists Google maps

5.8 Using GPS to find current location

Android GPS, Location Manager


One of the major features of android framework is location API. You can see, the location module
widely used in lot of apps those provides services like food ordering, transportation, health tracking,
social networking and lot more. The location module is part of Google Play Services and in the same
module geofencing and activity recognition are included.
In this article we are going to cover the basics of location API with an example app.

1. Introduction
Earlier, getting location is very easy with couple of API calls. But to provide more accurate locations
and optimizing the battery usage, Android introduced set APIs that should be combined to get the
best results from the location API. We will be using Fused Location API that combines signals
from GPS, Wi-Fi, and cell networks, as well as accelerometer, gyroscope, magnetometer and
other sensors to provide more accurate results.

1.1 Location Permissions


There are two permissions available to request location. The accuracy of the location is determined
by the kind of permission requested and priority level.
● ACCESS_COARSE_LOCATION: Gives location approximately equivalent to a city block.
● ACCESS_FINE_LOCATION: Gives precise location, sometimes in few meters or feet when
combined with High Priority accuracy.

1.2 Receiving Location Updates


● getLastLocation(): Returns the recent available location. When location is not available, it
returns null.
● Location Settings: In order to get the location, proper settings has to enabled in the device such
as GPS or Wifi. Instead of requesting the user to enable them separately, you can use Settings
Client to check whether proper settings are enabled or not. If enabled, you can proceed with
location updates or user will be shown a dialog to turn on the required hardware as shown
below.

● Update Interval: This interval defines the rate in milliseconds at which your app prefers the
location updates. Your app can receive updates lesser or higher than this rate if other apps
requested location updates higher than your value. Let’s say your app requests updates every
10secs, if other app is requesting updates at 5secs, your app might receives the same updates
ignoring the 10sec value.
● Fastest Update Interval: This is the rate at which your app can handle the location updates.
Without this value, you can see inconsistent user experience if your app can’t handle frequent
location updates.
● Priority: The accuracy of the location depends on the source of the hardware used. To define
this, Priority has to be mentioned while requesting the location. The priority can
be BALANCED, HIGH, LOWOR NO_POWER.

● 2. Creating New Project


1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from
templates.

2. Open res/strings.xml and add the below string resources.

3. Add ACCESS_FINE_LOCATION permission to your AndroidManifest.xml.

4. Open app/build.gradle and add location play service dependency. We also


need Dexter (Runtime Permissions) and ButterKnife (View Binding) libraries.

5. Open the layout file of main activity activity_main.xml and add the below code. In this layout,
few Buttons and TextViews are defined to toggle the location updates and display location
information.
6. Open MainActivity.java and add the below code. Initially the code might look heavy but with
couple of observations you can understand it easily.
● First we initialize all the location related clients such
as FusedLocationProviderClient, LocationRequest, LocationSettingsRequest, LocationCa
llback and SettingsClient in onCreate() method.
● While initializing, we define the interval setInterval(), fastest interval setFastestInterval() and
priority setPriority() on location request.
● Dexter is used to request the location permission before performing any location related
operations.
● startLocationUpdates() requests for location updates. First, it checks whether the location
settings are eanbled and once satisfied, the updates will be requested. Here SettingsClient is
used to check for settings configuration.
● The location updates will be received in LocationCallback and proper UI action is taken place.
If you really want to the location only once, you can call stopLocationUpdates() method
immediately after receiving the first location update.
● The location updates are paused and resume in onPause() and onResume() method to save the
batter power.
Run the app in emulator or on a real device to see it working

https://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

5.9 Animation -View animation and Drawable animation

You might also like