Module2 MAD
Module2 MAD
VTUPulse.com
Input controls and view focus:
Android applies a common name to all input controls called a view. The View class
represents the basic building block for UI components, including input controls. View is the
base class for classes that provide support for interactive UI components, such as buttons, text
fields, and layout managers.
The View that "has the focus" will be the component that receives user input. Focus indicates
which view is currently selected to receive input. Focus can be initiated by the user by
touching a View, such as a TextView or an EditText object. Focus can be programmatically
controlled; a programmer can requestFocus() on any View that is focusable.
Using buttons:
People like to press buttons. Show someone a big red button with a message that says "Do
not press" and the person will likely press it for the sheer pleasure of pressing a big red button
(that the button is forbidden is also a factor). When touched or clicked, a button performs an
1
Android notes Module 2
action. It is also referred to as a "push-button". A button is a rectangle or rounded
rectangle.
You can make a Button using:
Only text, as shown on the left side of the figure below.
Only an icon, as shown in the center of the figure below.
Both text and an icon, as shown on the right side of the figure below.
Android offers several types of buttons, including raised buttons and flat buttons as shown in
the figure below. These buttons have three states: normal, disabled, and pressed.
VTUPulse.com
In the above figure:
1. Raised button in three states: normal, disabled, and pressed.
2. Flat button in three states: normal, disabled, and pressed.
Normal state: In its normal state, the button looks like a raised button.
Disabled state: When the button is disabled, it is grayed out and it's not active in the
app's context. In most cases you would hide an inactive button, but there may be
times when you would want to show it as disabled.
Pressed state: The pressed state, with a larger background shadow, indicates that the
button is being touched or clicked. When you attach a callback to the button (such as
the OnClick attribute), the callback is called when the button is in this state
VTUPulse.com
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
... />
The best practice with text buttons is to define a very short word as a string resource
(button_text in the above example), so that the string can be translated. For example,
"Save" could be translated into French as "Enregistrer" without changing any of the
code.
3
Android notes Module 2
3. Choose Action Bar and Tab Items in the drop-down menu of the Configure Image Asset
dialog (see Image Asset Studio for a complete description of this dialog.)
4. Click the Clipart: image (the Android logo) to select a clipart image as the icon. A page of
icons appears as shown below. Click the icon you want to use.
5. You may want to make the following adjustments:
Choose HOLO_DARK from the Theme drop-down menu to sets the icon to be white against
a dark-colored (or black) background. Depending on the shape of the icon, you may want to
add padding to the icon so that the icon doesn't crowd the text. Drag the Padding slider to the
right to add more padding.
6. Click Next, and then click Finish in the Confirm Icon Path dialog. The icon name should
now appear in the app > res > drawable folder.
Vector images of a standard icon are automatically resized for different sizes of device
displays. To choose vector images, follow these steps:
1. Expand app > res in the Project view, and right-click (or Command-click) drawable.
2. Choose New > Vector Asset for an icon that automatically resizes itself for each display.
3. The Vector Asset Studio dialog appears for a vector asset. Click the Material Icon radio
VTUPulse.com
button, and then click the Choose button to choose an icon from the Material Design spec
(see Add Multi-Density Vector Graphics for a complete description of this dialog).
4. Click Next after choosing an icon, and click Finish to finish. The icon name should now
appear in the app > res > drawable folder
4
Android notes Module 2
VTUPulse.com
color resource:
android:background="@color/colorPrimary"
5
Android notes Module 2
Designing images as buttons:
You can turn any View, such as an ImageView, into a button by adding the android:onClick
attribute in the XML layout. The image for the ImageView must already be stored in the
drawables folder of your project.
Note: To bring images into your Android Studio project, create or save the image in JPEG
format, and copy the image file into the app > src > main > res > drawables folder of your
project.
VTUPulse.com
You should use a floating action button only to represent the primary action for a screen. For
example, the primary action for the Contacts app's main screen is adding a contact, as shown
in the figure above. A floating action button is the right choice if your app requires an action
to be persistent and readily available on a screen. Only one floating action button is
recommended per screen.
The floating action button uses the same type of icons that you would use for a button with an
icon, or for actions in the app bar at the top of the screen. You can add an icon as described
previously in "Choosing an icon for the button".
To use a floating action button in your Android Studio project, you must add the following
statement to your build.gradle (Module: app) file in the dependencies section: add
compile 'com.android.support:design:23.4.0'
To create a floating action button, use the FloatingActionButton class, which extends the
ImageButton class. You can add a floating action button to your XML layout as follows:
<android.support.design.widget.FloatingActionButton
6
Android notes Module 2
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/ic_fab_chat_button_white" />
Floating action buttons, by default, are 56 x 56 dp in size. It is best to use the default size
unless you need the smaller version to create visual continuity with other screen elements.
You can set the mini size (30 x 40 dp) with the app:fabSize attribute:
app:fabSize="mini"
To set it back to the default size (56 x 56 dp):
app:fabSize="normal"
VTUPulse.com
Button, ImageButton, or FloatingActionButton. For more information on event listeners, or
other types of UI events, read the Input Events.
7
Android notes Module 2
....
3. Define the onClick() method to be public , return void , and define a View as its only
parameter:
public void onClick(View v) {
// Do something in response to button click
}
4. Create a method to do something in response to the button click, such as perform an action.
VTUPulse.com
Other events can occur with UI elements, and you can use the callback methods already
defined in the event listener interfaces to handle them. The methods are called by the Android
framework when the view—to which the listener has been registered—is triggered by user
interaction. You therefore must set the appropriate listener to use the method. The following
are some of the listeners available in the Android framework and the callback methods
associated with each one:
onClick() from View.OnClickListener: Handles a click event in which the user
touches and then releases an area of the device display occupied by a view. The
onClick() callback has no return value.
onLongClick() from View.OnLongClickListener: Handles an event in which the user
maintains the touch over a view for an extended period. This returns a boolean to
indicate whether you have consumed the event and it should not be carried further.
That is, return true to indicate that you have handled the event and it should stop here;
return false if you have not handled it and/or the event should continue to any other
on-click listeners.
onTouch() from View.OnTouchListener: Handles any form of touch contact with the
screen including individual or multiple touches and gesture motions, including a
8
Android notes Module 2
press, a release, or any movement gesture on the screen (within the bounds of the UI
element). A MotionEvent is passed as an argument, which includes directional
information, and it returns a boolean to indicate whether your listener consumes this
event.
onFocusChange() from View.OnFocusChangeListener: Handles when focus moves
away from the current view as the result of interaction with a trackball or navigation
key.
onKey() from View.OnKeyListener: Handles when a key on a hardware device is
pressed while a view has focus.
VTUPulse.com
Toggle button: Select one state out of two or more states. Toggle buttons usually offer
two visible states, such as "on"and "off".
Spinner: Select one value from a set of values in a drop-down menu. Only one value
can be selected. Spinners are useful for three or more choices, and takes up little room
in your layout.
Checkboxes:
Use checkboxes when you have a list of options and the user may select any number of
choices, including no choices. Each checkbox is independent of the other checkboxes in the
list, so checking one box doesn't uncheck the others. (If you want to limit the user's selection
to only one item of a set, use radio buttons.) A user can also uncheck an already checked
checkbox.
Users expect checkboxes to appear in a vertical list, like a to-do list, or side-by-side
horizontally if the labels are short.
9
Android notes Module 2
Each checkbox is a separate instance of the CheckBox class. You create each checkbox using
a CheckBox element in your XML layout. To create multiple checkboxes in a vertical
orientation, use a vertical LinearLayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:id="@+id/checkbox1_chocolate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/chocolate_syrup" />
<CheckBox android:id="@+id/checkbox2_sprinkles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sprinkles" />
<CheckBox android:id="@+id/checkbox3_nuts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/crushed_nuts" />
</LinearLayout>
VTUPulse.com
Typically programs retrieve the state of checkboxes when a user touches or clicks a Submit
or Done button in the same activity, which uses the android:onClick attribute to call a method
such as onSubmit() :
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/submit"
android:onClick="onSubmit"/>
The callback method— onSubmit() in the above Button example—must be public , return
void , and define a View as a parameter (the view that was clicked). In this method you can
determine if a checkbox is selected by using the isChecked() method (inherited from
CompoundButton). The isChecked() method will return a (boolean) true if there is a
checkmark in the box. For example, the following statement assigns the boolean value of true
or false to checked depending on whether the checkbox is checked:
boolean checked = ((CheckBox) view).isChecked();
The following code snippet shows how the onSubmit() method might check to see which
checkbox is selected, using the resource id for the checkbox element:
10
Android notes Module 2
public void onSubmit(View view){
StringBuffer toppings = new
StringBuffer().append(getString(R.string.toppings_label));
if (((CheckBox) findViewById(R.id.checkbox1_chocolate)).isChecked()) {
toppings.append(getString(R.string.chocolate_syrup_text));
}
if (((CheckBox) findViewById(R.id.checkbox2_sprinkles)).isChecked()) {
toppings.append(getString(R.string.sprinkles_text));
}
if (((CheckBox) findViewById(R.id.checkbox3_nuts)).isChecked()) {
toppings.append(getString(R.string.crushed_nuts_text));
}
...
}
Radio buttons:
Use radio buttons when you have two or more options that are mutually exclusive—the user
must select only one of them.
VTUPulse.com
Users expect radio buttons to appear as a vertical list, or side-by-side horizontally if the labels
are short. Each radio button is an object of the RadioButton class. Radio buttons are normally
used together in a RadioGroup. When several radio buttons live inside a radio group,
checking one radio button unchecks all the others. You create each radio button using a
RadioButton element in your XML layout within a RadioGroup view group:
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="@id/orderintrotext">
<RadioButton
android:id="@+id/sameday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/same_day_messenger_service"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/nextday"
11
Android notes Module 2
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/next_day_ground_delivery"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Use the android:onClick attribute for each radio button to declare the click event handler
method for the radio button, which must be defined within the activity that hosts this layout.
In the above layout, clicking any radio button calls the same onRadioButtonClicked() method
in the activity, but you could create separate methods in the activity and declare them in each
radio button's android:onClick attribute. The click event handler method must be public ,
return void , and define a View as its only parameter (the view that was clicked). The
following shows one method, onRadioButtonClicked() , for all radio buttons, using switch
case statements to check the resource id for the radio button element to determine which one
was checked:
public void onRadioButtonClicked(View view) {
// Check to see if a button has been clicked.
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked.
VTUPulse.com
switch(view.getId()) {
case R.id.sameday:
if (checked)
// Same day service
break;
case R.id.nextday:
if (checked)
// Next day delivery
break;
case R.id.pickup:
if (checked)
// Pick up
break;
}
}
12
Android notes Module 2
Toggle buttons and switches:
A toggle input control lets the user change a setting between two states. Android provides the
ToggleButton class, which shows a raised button with "OFF" and "ON".
Examples of toggles include the On/Off switches for Wi-Fi, Bluetooth, and other options in
the Settings app.
Android also provides the Switch class, which is a short slider that looks like a rocker switch
offering two states (on and off). Both are extensions of the CompoundButton class.
VTUPulse.com
android:id="@+id/my_toggle"
android:text="
android:onClick="onToggleClick"/>
To respond to the toggle tap, declare an android:onClick callback method for the
ToggleButton . The method must be defined in the activity hosting the layout, and it must be
public , return void , and define a View as its only parameter (this will be the view that was
clicked). Use CompoundButton.OnCheckedChangeListener() to detect the state change of the
toggle. Create a CompoundButton.OnCheckedChangeListener object and assign it to the
button by calling setOnCheckedChangeListener() . For example, the onToggleClick() method
checks whether the toggle is on or off, and displays a toast message:
public void onToggleClick(View view) {
ToggleButton toggle = (ToggleButton) findViewById(R.id.my_toggle);
toggle.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
StringBuffer onOff = new StringBuffer().append("On or off? ");
13
Android notes Module 2
if (isChecked) { // The toggle is enabled
onOff.append("ON ");
} else { // The toggle is disabled
onOff.append("OFF ");
}
Toast.makeText(getApplicationContext(), onOff.toString(),
Toast.LENGTH_SHORT).show();
}
});
}
Using a switch:
A switch is a separate instance of the Switch class, which extends the CompoundButton class
just like ToggleButton. Create a toggle switch by using a Switch element in your XML
layout:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
VTUPulse.com
android:id="@+id/my_switch"
android:text="@string/turn_on_or_off"
android:onClick="onSwitchClick"/>
The android:text attribute defines a string that appears to the left of the switch, as shown
below:
To respond to the switch tap, declare an android:onClick callback method for the Switch —
the code is basically the same as for a ToggleButton . The method must be defined in the
activity hosting the layout, and it must be public , return void , and define a View as its only
parameter (this will be the view that was clicked). Use
CompoundButton.OnCheckedChangeListener() to detect the state change of the switch.
Create a CompoundButton.OnCheckedChangeListener object and assign it to the button by
calling setOnCheckedChangeListener() . For example, the onSwitchClick() method checks
whether the switch is on or off, and displays a toast message:
public void onSwitchClick(View view) {
14
Android notes Module 2
Switch aSwitch = (Switch) findViewById(R.id.my_switch);
aSwitch.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
StringBuffer onOff = new StringBuffer().append("On or off? ");
if (isChecked) { // The switch is enabled
onOff.append("ON ");
} else { // The switch is disabled
onOff.append("OFF ");
}
Toast.makeText(getApplicationContext(), onOff.toString(),
Toast.LENGTH_SHORT).show();
}
});
}
Spinners:
VTUPulse.com
A spinner provides a quick way to select one value from a set. Touching the spinner displays
a drop-down list with all available values, from which the user can select one.
If you have a long list of choices, a spinner may extend beyond your layout, forcing the user
to scroll it. A spinner scrolls automatically, with no extra code needed.
To create a spinner, use the Spinner class, which creates a view that displays individual
spinner values as child views, and lets the user pick one. Follow these steps:
1. Create a Spinner element in your XML layout, and specify its values using an array and
an ArrayAdapter.
2. Create the spinner and its adapter using the SpinnerAdapter class.
3. To define the selection callback for the spinner, update the Activity that uses the spinner to
implement the AdapterView.OnItemSelectedListener interface.
15
Android notes Module 2
Create the spinner UI element:
To create a spinner in your XML layout, add a Spinner element, which provides the drop-
down list:
<Spinner
android:id="@+id/label_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Spinner>
Specify the values for the spinner:
Use the adapter to fill the values for Spinner. An adapter is like a bridge, or intermediary,
between two incompatible interfaces. For example, a memory card reader acts as an adapter
between the memory card and a laptop. You plug the memory card into the card reader, and
plug the card reader into the laptop, so that the laptop can read the memory card.
VTUPulse.com
The SpinnerAdapter class, which implements the Adapter class, allows you to define two
different views: one that shows the data values in the spinner itself, and one that shows the
data in the drop-down list when the spinner is touched or clicked.
The values you provide for the spinner can come from any source, but must be provided
through a SpinnerAdapter, such as an ArrayAdapter if the values are available in an array.
The following shows a simple array called labels_array of predetermined values in the
strings.xml file:
<string-array name="labels_array">
<item>Home</item>
<item>Work</item>
<item>Mobile</item>
<item>Other</item>
</string-array>
16
Android notes Module 2
Create the spinner and its adapter:
Create the spinner, and set its listener to the activity that implements the callback methods.
The best place to do this is when the view is created in the onCreate() method. Follow these
steps (refer to the full onCreate() method at the end of
the steps):
1. Add the code below to the onCreate() method, which does the following:
2. Gets the spinner object you added to the layout using findViewById() to find it by its id (
label_spinner ).
3. Sets the onItemSelectedListener to whichever activity implements the callbacks ( this )
using the setOnItemSelectedListener() method.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the spinner.
Spinner spinner = (Spinner) findViewById(R.id.label_spinner);
if (spinner != null) {
spinner.setOnItemSelectedListener(this);
}
}
VTUPulse.com
4. Also in the onCreate() method, add a statement that creates the ArrayAdapter with the
string array:
// Create ArrayAdapter using the string array and default spinner layout.
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.labels_array, android.R.layout.simple_spinner_item);
5. Specify the layout the adapter should use to display the list of spinner choices by calling
the setDropDownViewResource() method of the ArrayAdapter class. For example, you can
use simple_spinner_dropdown_item as your layout:
// Specify the layout to use when the list of choices appears.
adapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
6. Use setAdapter() to apply the adapter to the spinner:
// Apply the adapter to the spinner.
spinner.setAdapter(adapter);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the spinner.
Spinner spinner = (Spinner) findViewById(R.id.label_spinner);
if (spinner != null) {
17
Android notes Module 2
spinner.setOnItemSelectedListener(this);
}
// Create ArrayAdapter using the string array and default spinner layout.
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.labels_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears.
adapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner.
if (spinner != null) {
spinner.setAdapter(adapter);
}
}
VTUPulse.com
Text input:
Use the EditText class to get user input that consists of textual characters, including numbers
and symbols. EditText extends the TextView class, to make the TextView editable.
Customizing an EditText object for user input
In the Layout Manager of Android Studio, create an EditText view by adding an EditText to
your layout with the following XML:
<EditText
android:id="@+id/edit_simple"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</EditText>
Enabling multiple lines of input:
By default, the EditText view allows multiple lines of input as shown in the figure below, and
suggests spelling corrections. Tapping the Return (also known as Enter) key on the on-screen
keyboard ends a line and starts a new line in the same EditText view.
18
Android notes Module 2
android:maxLength="5" : Set the maximum number of input characters to 5.
android:inputType="number" : Restrict text entry to numbers.
android:digits="01" : Restrict the digits entered to just "0" and "1".
android:textColorHighlight="#7cff88" : Set the background color of selected
(highlighted) text.
android:hint="@string/my_hint" : Set text to appear in the field that provides a hint
for the user, such as "Enter a message"
VTUPulse.com
string representing the data in the character sequence.
String showString = editText.getText().toString();
Tip: You can use the valueOf() method of the Integer class to convert the string to an
integer if the input is an integer.
19
Android notes Module 2
The Dialog class is the base class for dialogs, but you should avoid instantiating Dialog
directly unless you are creating a custom dialog. For standard Android dialogs, use one of the
following subclasses:
AlertDialog: A dialog that can show a title, up to three buttons, a list of selectable
items, or a custom layout.
DatePickerDialog or TimePickerDialog: A dialog with a pre-defined UI that lets the
user select a date or time.
Showing an alert dialog:
Alerts are urgent interruptions, requiring acknowledgement or action, that inform the user
about a situation as it occurs, or an action before it occurs (as in discarding a draft). You can
provide buttons in an alert to make a decision. For example, an alert dialog might require the
user to click Continue after reading it, or give the user a choice to agree with an action by
clicking a positive button (such as OK or Accept), or to disagree by clicking a negative
button (such as Disagree orCancel).
Use the AlertDialog subclass of the Dialog class to show a standard dialog for an alert. The
AlertDialog class allows you to build a variety of dialog designs. An alert dialog can have the
following regions (refer to the diagram below):
1. Title: A title is optional. Most alerts don't need titles. If you can summarize a decision in a
sentence or two by either asking a question (such as, "Discard draft?") or making a statement
related to the action buttons (such as, "Click OK to continue"), don't bother with a title. Use a
title if the situation is high-risk, such as the potential loss of connectivity or
VTUPulse.com
data, and the content area is occupied by a detailed message, a list, or custom layout.
2. Content area: The content area can display a message, a list, or other custom layout.
3. Action buttons: You should use no more than three action buttons in a dialog, and most
have only two.
Building the AlertDialog:
The AlertDialog.Builder class uses the builder design pattern.
Use AlertDialog.Builder to build a standard alert dialog and set attributes on the dialog. Use
setTitle() to set its title, setMessage() to set its message, and setPositiveButton() and
setNegativeButton() to set its buttons.
The following creates the dialog object ( myAlertBuilder ) and sets the title (the string
resource called alert_title ) and message (the string resource called alert_message ):
AlertDialog.Builder myAlertBuilder = new AlertDialog.Builder(MainActivity.this);
myAlertBuilder.setTitle(R.string.alert_title);
myAlertBuilder.setMessage(R.string.alert_message);
Setting the button actions for the alert dialog
Use the setPositiveButton() and setNegativeButton() methods of the AlertDialog.Builder
class to set the button actions for the alert dialog. These methods require a title for the button
20
Android notes Module 2
(supplied by a string resource) and the DialogInterface.OnClickListener class that defines the
action to take when the user presses the button:
myAlertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User clicked OK button.
}
});
myAlertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User clicked the CANCEL button.
}
});
Displaying the dialog
To display the dialog, call its show() method:
alertDialog.show();
VTUPulse.com
Android provides dialogs, called pickers, for picking a time or a date. Use them to ensure that
your users pick a valid time or date that is formatted correctly and adjusted to the user's
locale. Each picker provides controls for selecting each part of the time (hour, minute,
AM/PM) or date (month, day, year).
When showing a picker, you should use an instance of DialogFragment, a subclass of
Fragment, which displays a dialog window floating on top of its activity's window. A
fragment is a behavior or a portion of user interface within an activity. It's like a mini-activity
within the main activity, with its own individual lifecycle. A fragment receives its own input
events, and you can add or remove it while the main activity is running. You might combine
multiple fragments in a single activity to build a multiple-pane user interface, or reuse a
fragment in multiple activities.
Adding a fragment
To add a fragment for the date picker, create a blank fragment (DatePickerFragment)
without a layout XML, and without factory methods or interface callbacks:
1. Expand app > java > com.example.android.DateTimePickers and select MainActivity.
21
Android notes Module 2
2. Choose File > New > Fragment > Fragment (Blank), and name the fragment
DatePickerFragment. Uncheck all three checkbox options so that you do not create a layout
XML, do not include fragment factory methods, and do not include interface callbacks. You
don't need to create a layout for a standard picker. Click Finish to create the fragment.
Extending DialogFragment for the picker:
Edit the DatePickerFragment class definition to extend DialogFragment, and implement
DatePickerDialog.OnDateSetListener to create a standard date picker with a listener:
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
...
}
2. Android Studio also shows a red light bulb icon in the left margin, prompting you to
implement methods. Click the icon and, with onDateSet already selected and the "Insert
@Override" option checked, click OK to create the empty
onDateSet() method.
Android Studio then automatically adds the following in the import block at the top:
import android.widget.DatePicker;
VTUPulse.com
3. Replace onCreateView() with onCreateDialog() :
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
}
When you extend DialogFragment , you should override the onCreateDialog() callback
method, rather than onCreateView.
Setting the defaults and returning the picker:
To set the default date in the picker and return it as an object you can use, follow these steps:
1. Add the following code to the onCreateDialog() method to set the default date for the
picker:
// Use the current date as the default date in the picker.
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
22
Android notes Module 2
As you enter Calendar , you are given a choice of which Calendar library to import. Choose
this one: import java.util.Calendar;
2. Add the following statement to the end of the method to create a new instance of the date
picker and return it:
return new DatePickerDialog(getActivity(), this, year, month, day);
Showing the picker
In the Main Activity, you need to create a method to show the date picker. Follow these
steps:
1. Create a method to instantiate the date picker dialog fragment:
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
2. You can then use showDatePickerDialog() with the android:onClick attribute for a button
or other input control:
<Button
android:id="@+id/button_date"
...
VTUPulse.com
android:onClick="showDatePickerDialog"/>
Processing the user's picker choice:
The onDateSet() method is automatically called when the user makes a selection in the date
picker, so you can use this method to do something with the chosen date. Follow these steps:
1. To make the code more readable, change the onDateSet() method's parameters from int i ,
int i1 , and int i2 to int year , int month , and int day :
public void onDateSet(DatePicker view, int year, int month, int day) {
2. Open MainActivity and add the processDatePickerResult() method signature that takes the
year , month , and day as arguments:
public void processDatePickerResult(int year, int month, int day) {
}
3. Add the following code to the processDatePickerResult() method to convert the month ,
day , and year to separate strings:
String month_string = Integer.toString(month+1);
String day_string = Integer.toString(day);
23
Android notes Module 2
String year_string = Integer.toString(year);
4. Add the following after the above code to concatenate the three strings and include slash
marks for the U.S. date format:
String dateMessage = (month_string + "/" +day_string + "/" + year_string);
5. Add the following after the above statement to display a Toast message:
Toast.makeText(this, "Date: " + dateMessage, Toast.LENGTH_SHORT).show();
6. Extract the hard-coded string "Date: " into a string resource named date . This
automatically replaces the hardcoded string with getString(R.string.date) . The code for the
processDatePickerResult() method should now look like this:
public void processDatePickerResult(int year, int month, int day) {
String month_string = Integer.toString(month + 1);
String day_string = Integer.toString(day);
String year_string = Integer.toString(year);
// Assign the concatenated strings to dateMessage.
String dateMessage = (month_string + "/" + day_string + "/" + year_string);
Toast.makeText(this, getString(R.string.date) + dateMessage,
Toast.LENGTH_SHORT).show();
}
VTUPulse.com
7. Open DatePickerFragment, and add the following to the onDateSet() method to invoke the
processDatePickerResult() method in MainActivity and pass it the year , month , and day :
public void onDateSet(DatePicker view, int year, int month, int day) {
// Set the activity to the Main Activity.
MainActivity activity = (MainActivity) getActivity();
// Invoke Main Activity's processDatePickerResult() method.
activity.processDatePickerResult(year, month, day);
}
Recognizing gestures:
A touch gesture occurs when a user places one or more fingers on the touch screen, and your
app interprets that pattern of touches as a particular gesture, such as a long touch, double-tap,
fling, or scroll.
Android provides a variety of classes and methods to help to create and detect gestures.
Although your app should not depend on touch gestures for basic behaviors (since the
24
Android notes Module 2
gestures may not be available to all users in all contexts), adding touch-based interaction to
your app can greatly increase its usefulness and appeal.
Detecting common gestures:
If your app uses common gestures such as double tap, long press, fling, and so on, you can
take advantage of the GestureDetector class for detecting common gestures.
GestureDetectorCompat lets you detect common gestures without processing the individual
touch events yourself. It detects various gestures and events using MotionEvent objects,
which report movements by a finger (or mouse, pen, or trackball).
The following snippets show how you would use GestureDetectorCompat and the
GestureDetector.SimpleOnGestureListener class.
1. To use GestureDetectorCompat, create an instance ( mDetector in the snippet below) of the
GestureDetectorCompat class, using the onCreate() method in the activity (such as
MainActivity):
public class MainActivity extends Activity {
private GestureDetectorCompat mDetector;
@Override
public void onCreate(Bundle savedInstanceState) {
VTUPulse.com
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
}
...
}
When you instantiate a GestureDetectorCompat object, one of the parameters it takes is a
class you must create — MyGestureListener in the above snippet—that does one of the
following:
implements the GestureDetector.OnGestureListener interface, to detect all standard
gestures, or
extends the GestureDetector.SimpleOnGestureListener class, which you can use to
process only a few gestures by overriding the methods you need. Some of the
methods it provides include onDown(), onLongPress(), onFling(), onScroll(), and
onSingleTapUp().
25
Android notes Module 2
1. Create the class MyGestureListener as a separate activity (MyGestureListener ) to extend
GestureDetector.SimpleOnGestureListener , and override the onFling() and onDown()
methods to show log statements about the event:
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
@Override
public boolean onDown(MotionEvent event) {
Log.d(DEBUG_TAG,"onDown: " + event.toString());
return true;
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.d(DEBUG_TAG, "onFling: " +
event1.toString()+event2.toString());
return true;
}
}
VTUPulse.com
2. To intercept(Capture) touch events, override the onTouchEvent() callback of the
GestureDetectorCompat class in MainActivity:
@Override
public boolean onTouchEvent(MotionEvent event){
this.mDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
Detecting all gestures:
To intercept touch events in an activity or view, override the onTouchEvent() callback as
shown in the snippet below. You can use the getActionMasked() method of the
MotionEventCompat class to extract the action the user performed from the event parameter.
public class MainActivity extends Activity {
...
// This example shows an Activity, but you would use the same approach if
// you were subclassing a View.
26
Android notes Module 2
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_CANCEL) :
Log.d(DEBUG_TAG,"Action was CANCEL");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
VTUPulse.com
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
Menus:
Types of menus:
A menu is a set of options the user can select from to perform a function, such as searching
for information, saving information, editing information, or navigating to a screen. Android
offers the following types of menus, which are useful for different situations (refer to the
figure below):
27
Android notes Module 2
1. Options menu: Appears in the app bar and provides the primary options that affect using
the app itself. Examples of menu options: Search to perform a search, Bookmark to save a
link to a screen, and Settings to navigate to the Settings screen.
2. Context menu: Appears as a floating list of choices when the user performs a long tap on
an element on the screen. Examples of menu options: Edit to edit the element, Delete to
delete it, and Share to share it over social media.
3. Contextual action bar: Appears at the top of the screen overlaying the app bar, with action
items that affect the selected element(s). Examples of menu options: Edit, Share, and Delete
for one or more selected elements.
VTUPulse.com
4. Popup menu: Appears anchored to a view such as an ImageButton, and provides an
overflow of actions or the second part of a two-part command. Example of a popup menu: the
Gmail app anchors a popup menu to the app bar for the message view with Reply, Reply All,
and Forward.
The app bar and options menu:
The app bar (also called the action bar) is a dedicated space at the top of each activity screen.
When you create an activity from a template (such as Empty Template), an app bar is
automatically included for the activity in a CoordinatorLayout root view group at the top of
the view hierarchy.
The app bar by default shows the app title, or the name defined in AndroidManifest.xml by
the android:label attribute for the activity. It may also include the Up button for navigating up
to the parent activity.
The options menu in the app bar provides navigation to other activities in the app, or the
primary options that affect using the app itself.
The options menu appears in the right corner of the app bar.
The app bar is split into four different functional areas that apply to most apps:
28
Android notes Module 2
1. Navigation button or Up button: Use a navigation button in this space to open a navigation
drawer, or use an Up button for navigating up through your app's screen hierarchy to the
parent activity. Both are described in the next chapter.
2. Title: The title in the app bar is the app title, or the name defined in AndroidManifest.xml
by the android:label attribute for the activity.
3. Action icons for the options menu: Each action icon appears in the app bar and represents
one of the options menu's most frequently used items. Less frequently used options menu
items appear in the overflow options menu.
4. Overflow options menu: The overflow icon opens a popup with option menu items that are
not shown as icons in the app bar.
VTUPulse.com
Adding the options menu:
Android provides a standard XML format to define options menu items. Instead of building
the menu in your activity's code, you can define the menu and all its items in an XML menu
resource. A menu resource defines an application menu (optionsmenu, context menu, or
popup menu) that can be inflated with MenuInflater, which loads the resource as a Menu
object in your activity or fragment.
1. XML menu resource. Create an XML menu resource file for the menu items, and assign
appearance and position attributes as described in the next section.
29
Android notes Module 2
2. Inflating the menu. Override the onCreateOptionsMenu() method in your activity or
fragment to inflate the menu.
3. Handling menu item clicks. Menu items are views, so you can use the android:onClick
attribute for each menu item. However, the onOptionsItemSelected() method can handle all
the menu item clicks in one place, and determine which menu item was clicked, which makes
your code easier to understand.
4. Performing actions. Create a method to perform an action for each options menu item.
Adding icons for menu items:
To specify icons for actions, you need to first add the icons as image assets to the drawable
folder by following these steps (see Image Asset Studio for a complete description):
1. Expand res in the Project view, and right-click (or Command-click) drawable.
2. Choose New > Image Asset. The Configure Image Asset dialog appears.
3. Choose Action Bar and Tab Items in the drop-down menu.
4. Edit the name of the icon (for example, ic_order_white for the Order menu item).
5. Click the clipart image (the Android logo) to select a clipart image as the icon. A page of
icons appears. Click the icon you want to use.
VTUPulse.com
6. (Optional) Choose HOLO_DARK from the Theme drop-down menu. This sets the icon to
be white against a darkcolored (or black) background. Click Next.
7. Click Finish in the Confirm Icon Path dialog.
Icon and appearance attributes:
Use the following attributes to govern the menu item's appearance: android:icon : An image
to use as the menu item icon. For example, the following menu item defines ic_order_white
as its icon:
<item
android:id="@+id/action_order"
android:icon="@drawable/ic_order_white"
android:orderInCategory="40"
app:showAsAction="ifRoom"
android:onClick="onFavoritesClick"
android:title="@string/action_order"/>
Use the android:orderInCategory attribute to specify the order in which the menu items
appear in the menu, with the lowest number appearing higher in the menu. This is usually the
order of importance of the item within the menu.
30
Android notes Module 2
Use the app:showAsAction attribute to show menu items as icons in the app bar, with the
following values:
"always" : Always place this item in the app bar. Use this only if it's critical that the
item appear in the app bar (such as a Search icon). If you set multiple items to always
appear in the app bar, they might overlap something else in the app bar, such as the
app title.
"ifRoom" : Only place this item in the app bar if there is room for it. If there is not
enough room for all the items marked "ifRoom" , the items with the lowest
orderInCategory values are displayed in the app bar, and the remaining items are
displayed in the overflow menu.
"never" : Never place this item in the app bar. Instead, list the item in the app bar's
overflow menu.
"withText" : Also include the title text (defined by android:title ) with the item. The
title text appears anyway if the item appears in the overflow menu, so this attribute is
used primarily to include the title with the icon in the app bar.
Contextual menu:
VTUPulse.com
Use a contextual menu to allow users to take an action on a selected view. You can provide a
context menu for any View, but they are most often used for items in a RecyclerView,
GridView, or other view collections in which the user can perform direct actions on each
item.
Android provides two kinds of contextual menus:
A context menu, shown on the left side in the figure below, appears as a floating list
of menu items when the user performs a long tap on a view element on the screen. It
is typically used to modify the view element or use it in some fashion. For example, a
context menu might include Edit to edit a view element, Delete to delete it, and
Share to share it over social media. Users can perform a contextual action on one
view element at a time.
A Contextual action bar, shown on the right side of the figure below, appears at the
top of the screen in place of the app bar or underneath the app bar, with action items
that affect the selected view element(s). Users can perform an action on multiple view
elements at once (if your app allows it).
31
Android notes Module 2
Floating context menu:
Steps:
Follow these steps to create a floating context menu for one or more view elements (refer to
figure above):
1. Create an XML menu resource file for the menu items, and assign appearance and position
attributes (as described in the previous section).
2. Register a view to the context menu using the registerForContextMenu() method of the
Activity class.
VTUPulse.com
3. Implement the onCreateContextMenu() method in your activity or fragment to inflate the
menu.
4. Implement the onContextItemSelected() method in your activity or fragment to handle
menu item clicks.
5. Create a method to perform an action for each context menu item.
32
Android notes Module 2
In the above figure:
1. Contextual action bar. The bar offers three actions on the right side (Edit, Share, and
Delete) and the Done button (left arrow icon) on the left side.
2. View. View on which a long-click triggers the contextual action bar.
The contextual action bar appears only when contextual action mode, a system
implementation of ActionMode, occurs as a result of the user performing a long-click on the
View.
ActionMode is a UI mode that allows you replace parts of the normal UI interactions
temporarily. For example, text selection is implemented as an ActionMode, as are contextual
actions that work on a selected item on the screen. Selecting a section of text or long-clicking
a view triggers ActionMode.
Follow these steps to create a contextual action bar (refer to the figure below):
1. Create an XML menu resource file for the menu items, and assign an icon to each one (as
described in a previous section).
2. Set the long-click listener to the view that should trigger the contextual action bar using the
setOnLongClickListener()method. Call startActionMode() within the
setOnLongClickListener() method when the user performs a long tap on the view.
VTUPulse.com
3. Implement the ActionMode.Callback interface to handle the ActionMode lifecycle. Include
in this interface the action for responding to a menu item click in the onActionItemClicked()
callback method.
Popup menu:
A PopupMenu is a vertical list of items anchored to a View. It appears below the anchor view
if there is room, or above the view otherwise.
A popup menu is typically used to provide an overflow of actions (similar to the overflow
action icon for the options menu) or the second part of a two-part command. Use a popup
33
Android notes Module 2
menu for extended actions that relate to regions of content in your activity. Unlike a context
menu, a popup menu is anchored to a Button (View), is always available, and it's actions
generally do not affect the content of the View.
For example, the Gmail app uses a popup menu anchored to the overflow icon in the app bar
when showing an email message. The popup menu items Reply, Reply All, and Forward are
related to the email message, but don't affect or act on the message. Actions in a popup menu
should not directly affect the corresponding content (use a contextual menu to directly affect
selected content). As shown below, a popup can be anchored to the overflow action button in
the action bar.
Steps:
1. Create an XML menu resource file for the popup menu items, and assign appearance and
VTUPulse.com
position attributes (as described in a previous section).
2. Add an ImageButton for the popup menu icon in the XML activity layout file.
3. Assign onClickListener() to the button.
4.Override the onClick() method to inflate the popup menu and register it with
PopupMenu.OnMenuItemClickListener.
5. Implement the onMenuItemClick() method.
6. Create a method to perform an action for each popup menu item.
Screen Navigation:
Two forms of Navigation
Back navigation: Users can navigate back to the previous screen using the Back
button.
Hierarchical navigation: Users can navigate through a hierarchy of screens organized
with a parent screen for every set of child screens.
34
Android notes Module 2
Ancestral or up navigation
● provided by the app's action bar
● controlled by defining parent-child relationships between activities in the Android
manifest
Hierarchical Navigation:
Types of hierarchical navigation
● Descendant navigation
○ Down from a parent screen to one of its children
○ From a list of headlines to a story summary to a story
● Ancestral navigation
○ Up from a child or sibling screen to its parent
○ From a story summary back to the headlines
● Lateral navigation
VTUPulse.com
○ From one sibling to another sibling
○ Swiping between tabbed views
35
Android notes Module 2
2. Navigation drawer
3. Navigation drawer menu item
A good example of a navigation drawer is in the Gmail app, which provides access to the
Inbox, labeled email folders, and settings. The best practice for employing a navigation
drawer is to provide descendant navigation from the parent activity to all of the other
activities or fragments in an app.
To make a navigation drawer in your app, you need to do the following:
1. Create the following layouts:
A navigation drawer as the activity layout's root view.
A navigation view for the drawer itself.
An app bar layout that will include a navigation icon button.
A content layout for the activity that displays the navigation drawer.
A layout for the navigation drawer header.
2. Populate the navigation drawer menu with item titles and icons.
3. Set up the navigation drawer and item listeners in the activity code.
4. Handle the navigation menu item selections.
VTUPulse.com
Lateral navigation with tabs and swipes:
Lateral navigation
● Between siblings
● From a list of stories to a list in a different tab
● From story to story under the same tab
Steps for implementing tabs
1. Defining the tab layout. The main class used for displaying tabs is TabLayout. It provides a
horizontal layout to display tabs. You can show the tabs below the app bar.
2. Implementing a Fragment for each tab content screen. A fragment is a behavior or a
portion of user interface within an activity. It's like a mini-activity within the main activity,
with its own own lifecycle. One benefit of using fragments for the tab content is that you can
isolate the code for managing the tab content in the fragment.
3. Adding a pager adapter. Use the PagerAdapter class to populate "pages" (screens) inside of
a ViewPager, which is a layout manager that lets the user flip left and right through screens of
data. You supply an implementation of a PagerAdapter to generate the screens that the view
36
Android notes Module 2
shows. ViewPager is most often used in conjunction with Fragment, which is a convenient
way to supply and manage the lifecycle of each screen.
4. Creating an instance of the tab layout, and set the text for each tab.
5. Using PagerAdapter to manage screen ("page") views. Each screen is represented by its
own fragment.
6. Setting a listener to determine which tab is tapped.
RecyclerView
When you display a large number of items in a scrollable list, most items are not visible. For
example, in a long list of words or many news headlines, the user only sees a small number of
list items at a time.
The RecyclerView class is a more advanced and flexible version of ListView. It is a container
for displaying large data sets that can be scrolled very efficiently by maintaining a limited
number of views.
RecyclerView components
To display your data in a RecyclerView, you need the following parts:
VTUPulse.com
Data. It doesn't matter where the data comes from. You can create the data locally, as
you do in the practical, get it from a database on the device as you will do in a later
practical, or pull it from the cloud.
A RecyclerView. The scrolling list that contains the list items. An instance of
RecyclerView as defined in your activity's layout file to act as the container for the
views.
Layout for one item of data. All list items look the same, so you can use the same
layout for all of them. The itemlayout has to be created separately from the activity's
layout, so that one item view at a time can be created and filled with data.
A layout manager. The layout manager handles the organization (layout) of user
interface components in a view. All view groups have layout managers. For the
LinearLayout, the Android system handles the layout for you. RecyclerView requires
an explicit layout manager to manage the arrangement of list items contained within
it. This layout could be vertical, horizontal, or a grid. The layout manager is an
instance of Recyclerview. LayoutManager to organize the layout of the items in the
RecyclerView
37
Android notes Module 2
An adapter. The adapter connects your data to the RecyclerView. It prepares the data
and how will be displayed in a view holder. When the data changes, the adapter
updates the contents of the respective list item view in the RecyclerView. And an
adapter is an extension of RecyclerView.Adapter. The adapter uses a ViewHolder to
hold the views that constitute each item in the RecyclerView, and to bind the data to
be displayed into the views that display it.
A view holder. The view holder extends the ViewHolder class. It contains the view
information for displaying one item from the item's layout.
A view holder used by the adapter to supply data, which is an extension of
RecyclerView.ViewHolder
The diagram below shows the relationship between these compoments.
VTUPulse.com
Drawables, Styles, and Themes
Style Attributes, Themes.
Material Design:
Material Design is a visual(diagram) design philosophy(Idea) that Google created in 2014.
The aim of Material Design is a unified(uniform) user experience across platforms and device
sizes.
The aim of Material Design is that user has to experience uniform design across platforms
and device sizes.
Material Design includes a set of guidelines for style, layout, motion, and other aspects of app
design. This chapter focuses only on Material Design for mobile apps on Android.
Principles of Material Design:
The "material" metaphor
In Material Design, elements in your Android app behave like real world materials: they cast
shadows, occupy space, and interact with each other.
38
Android notes Module 2
Bold, graphic, intentional
Material Design involves deliberate color choices, edge-to-edge imagery, large-scale
typography, and intentional white space that create a bold and graphic interface.
VTUPulse.com
39