Unit-1: Basic User Interface Screen Elements
Unit-1: Basic User Interface Screen Elements
Screen elements 1
Unit Structure
1.0. Learning Objectives
1.1. Introduction
1.3. TextView
1.4. EditText
1.5. AutoCompleteTextView
1.6. Spinner
1.7. Buttons
1.10. Pickers
1.14. Activities
148
1.0 Learning Objective
1.1 Introduction
Most Android applications inevitably need some form of user interface. In this unit,we
will discuss the user interface elements available within the Android Software
DevelopmentKit (SDK). Some of these elements display information to the user,
whereas othersgather information from the user.
You learn how to use a variety of different components and controls to build a
screenand how your application can listen for various actions performed by the user.
Finally, youlearn how to style controls and apply themes to entire screens.
Before we go any further, we need to define a few terms.This gives you a better
understandingof certain capabilities provided by the Android SDK before they are
fully introduced.First, let’s talk about the View class.
This class represents the basic building block for user interface components. A View
occupies a rectangular area on the screen and is responsible for drawing and event
handling. View is the base class for widgets, which are used to create interactive UI
components (buttons, text fields, etc.). The ViewGroup subclass is the base class for
149
layouts, which are invisible containers that hold other Views (or other ViewGroups)
and define their layout properties.
All of the views in a window are arranged in a single tree. You can add views either
from code or by specifying a tree of views in one or more XML layout files. There are
many specialized subclasses of views that act as controls or are capable of
displaying text, images, or other content.
Once you have created a tree of views, there are typically a few types of common
operations you may wish to perform:
Set properties: for example setting the text of a TextView. The available properties
and the methods that set them will vary among the different subclasses of views.
Note that properties that are known at build time can be set in the XML layout files.
Set focus: The framework will handle moving focus in response to user input. To
force focus to a specific view, call requestFocus().
Set up listeners: Views allow clients to set listeners that will be notified when
something interesting happens to the view. For example, all views will let you set a
listener to be notified when the view gains or loses focus. You can register such a
listener using setOnFocusChangeListener(android.view.View.OnFocusChangeListener).
Other view subclasses offer more specialized listeners. For example, a Button
exposes a listener to notify clients when the button is clicked.
150
Introduction to Android Layout
One special type of control found within the android.widget package is called a
layout.A layout control is still a View object, but it doesn’t actually draw anything
specific on thescreen. Instead, it is a parent container for organizing other controls
(children). Layoutcontrols determine how and where on the screen child controls are
drawn. Each type oflayout control draws its children using particular rules. For
instance, the LinearLayoutcontrol draws its child controls in a single horizontal row or
a single vertical column. Similarly,a TableLayout control displays each child control
in tabular format (in cells withinspecific rows and columns).
By necessity, we use some of the layout View objectswithin this unit to illustrate how
to use the controls previously mentioned.However, we don’t go into the details of the
various layout types available as part of theAndroid SDK until the next unit. We will
lean in more details about layout in next unit.
1.3 TextView
TextView is a user interface element that displays text to the user. Following table
shows important XML Attributes of TextView control.
Attribute Description
id id is an attribute used to uniquely identify a text view
gravity The gravity attribute is an optional attribute which is used to control the
alignment of the text like left, right, center, top, bottom, center_vertical,
center_horizontal etc.
text text attribute is used to set the text in a text view.
textColor textColor attribute is used to set the text color of a text view. Color
value is in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
textSize textSize attribute is used to set the size of text of a text view. We can
set the text size in sp(scale independent pixel) or dp(density pixel).
textStyle textStyle attribute is used to set the text style of a text view. The
possible text styles are bold, italic and normal.
151
background background attribute is used to set the background of a text view. We
can set a color or a drawable in the background of a text view
padding padding attribute is used to set the padding from left, right, top or
bottom.
Table-18
The following code sample shows a typical use, with an XML layout and code to
modify the contents of the text view:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is TextView"
android:layout_centerInParent="true"
android:textSize="35sp"
android:padding="15dp"
android:textColor="#aaa"
android:background="#fff"/>
</LinearLayout>
This code sample demonstrates how to modify the contents of the text view defined
in the previous XML layout:
152
helloTextView.setText(R.string.user_greeting);
}
}
To display this TextView on the screen, all your Activity needs to do is call
thesetContentView() method with the layout resource identifier in which you defined
in thepreceding XML shown.
You can change the text displayed programmatically by callingthe setText() method
on the TextView object. Retrieving the text is done with thegetText() method.To
customize the appearance of TextView we can use Styles and Themes.
1.4 EditText
EditText is a user interface element for entering and modifying text.Following table
shows important XML Attributes of EditText control.
Attribute Description
id This is an attribute used to uniquely identify an edit text
gravity The gravity attribute is an optional attribute which is used to control
the alignment of the text like left, right, center, top, bottom,
center_vertical, center_horizontal etc.
text This attribute is used to set the text in a text view.
hint It is an attribute used to set the hint i.e. what you want user to enter in
this edit text. Whenever user start to type in edit text the hint will
automatically disappear.
lines Defineshow many lines tall the input box is. If this isnot set, the entry
field grows as the user enters text.
textColorHint It is an attribute used to set the color of displayed hint.
textColor This attribute is used to set the text color of aedit text. Color value is
in the form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
textSize This attribute is used to set the size of text of aedit text. We can set
the text size in sp(scale independent pixel) or dp(density pixel).
153
textStyle This attribute is used to set the text style of aedit text. The possible
text styles are bold, italic and normal.
background This attribute is used to set the background of aedit text. We can set
a color or a drawable in the background of a edit text
padding Paddingattribute is used to set the padding from left, right, top or
bottom.
Table-19
Following layout code shows a basic EditText element.
<EditText
android:id=”@+id/txtName”
android:layout_height=”wrap_content”
android:hint=”Full Name”
android:lines=”4”
android:layout_width=”fill_parent” />
The EditText object is essentially an editable TextView. You can readtext from it in
by using the getText() method.You can also set initial text to draw in the text entry
area using the setText() method.You can also highlight a portion of the text fromcode
bycall to setSelection() method and a call to selectAll() method highlights theentire
text entry field.
By default, the user can perform a long press to bring up a context menu.This
providesto the user some basic copy, cut, and paste operations as well as the ability
tochange the input method and add a word to the user’s dictionary of frequently
usedwords. You can set theeditable attribute to false, so the user cannot edit the text
in the field but can still copytext out of it using a long press.
1.5 AutoCompleteTextView
154
of suggestions is displayed in drop down menu from which user can choose an item
which actually replace the content of EditBox with that.
It is a subclass of EditText class so we can inherit all the properties of EditText in a
AutoCompleteTextView.
<AutoCompleteTextView
android:id="@+id/ac"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Auto Suggestions EditText"/>
String v = ac.getText().toString();
155
(A) Label (B) EditText (C) TextBox (D) TextView
e) ___________is a user interface element for entering and modifying text.
(A) Label (B) EditText (C) TextBox (D) TextView
f) AutoCompleteTextView is a view i.e. similar to ________except that it displays a
list of completion suggestions automatically while the user is typing.
1.6 Spinner
In Android, Spinner provides a quick way to select one value from a set of values. It
is similar to dropdown list in other programming language. In a default state, a
spinner shows its currently selected value. It provides an easy way to select a value
from a known set.Following table shows important XML Attributes of spinner control.
Attribute Description
dropDownHorizontalOffset Amount of pixels by which the drop down should be
offset horizontally.
dropDownSelector List selector to use for spinnerMode="dropdown"
display.
156
dropdown 1 Spinner options will be presented to
the user as an inline dropdown
anchored to the spinner widget itself.
Table-20
As with the auto-complete method, the possible choices for a spinner can come from
an Adapter.You can also set the available choices in the layout definition by usingthe
entries attribute with an array resource. Following is an XML layout for showing
spinner
<Spinner
android:id=”@+id/Spinner01”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:entries=”@array/colors”
android:prompt=”@string/spin_prompt” />
This places a Spinner control on the screen.When the user selects it, apop-up shows
the prompt text followed by a list of the possible choices.This list allowsonly a single
item to be selected at a time, and when one is selected, the pop-up goes away.
First, the entries attribute is set to thevalues that shows by assigning it to an array
resource, referred to here as @array/colors.
The choices you provide for the spinner can come from any source, but must be
provided through a SpinnerAdapter, such as an ArrayAdapter if the choices are
available in an array or a CursorAdapter if the choices are available from a database
query.
For instance, if the available choices for your spinner are pre-determined, you can
provide them with a string array defined in a string resource file:
157
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
With an array such as this one, you can use the following code in
your Activity or Fragment to supply the spinner with the array using an instance
of ArrayAdapter:
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array,android.R.layout.simple_spinner_item);
158
Call setAdapter() to apply the adapter to your Spinner.
When the user selects an item from the drop-down, the Spinner object receives an
on-item-selected event.
159
If you implement the AdapterView.OnItemSelectedListener interface with your
Activity or Fragment (such as in the example above), you can pass this as the
interface instance.
1.7 Button
A user interface element the user can tap or click to perform an action.To display a
button in an activity, add a button to the activity's layout XML file:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:drawableLeft="@drawable/button_icon"
... />
To specify an action when the button is pressed, set a click listener on the button
object in the corresponding activity code:
Figure-61
public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_layout_id);
160
The above snippet creates an instance of View.OnClickListener and wires the
listener to the button using setOnClickListener(View.OnClickListener). As a result,
the system executes the code you write in onClick(View) after the user presses the
button.
Every button is styled using the system's default button background, which is often
different from one version of the platform to another. If you are not satisfied with the
default button style, you can customize it.
1.8 Checkbox
Figure-62
To create each checkbox option, create a CheckBox in your layout. Because a set of
checkbox options allows the user to select multiple items, each checkbox is
managed separately and you must register a click listener for each one.
When the user selects a checkbox, the CheckBox object receives an on-click event.
To define the click event handler for a checkbox, add the android:onClick attribute to
the <CheckBox> element in your XML layout. The value for this attribute must be the
name of the method you want to call in response to a click event. The Activity
hosting the layout must then implement the corresponding method.
Within the Activity that hosts this layout, the following method handles the click event
for both checkboxes:
Radio buttons allow the user to select one option from a set. You should use radio
buttons for optional sets that are mutually exclusive if you think that the user needs
to see all available options side-by-side. If it's not necessary to show all options side-
by-side, use a spinner instead.
Figure-63
To create each radio button option, create a RadioButton in your layout. However,
because radio buttons are mutually exclusive, you must group them together inside a
RadioGroup. By grouping them together, the system ensures that only one radio
button can be selected at a time.
When the user selects one of the radio buttons, the corresponding RadioButton
object receives an on-click event.
To define the click event handler for a button, add the android:onClick attribute to the
<RadioButton> element in your XML layout. The value for this attribute must be the
name of the method you want to call in response to a click event. The Activity
hosting the layout must then implement the corresponding method.
163
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButtonandroid:id="@+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pirates"
android:onClick="onRadioButtonClicked"/>
<RadioButtonandroid:id="@+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ninjas"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Within the Activity that hosts this layout, the following method handles the click event
for both radio buttons:
Android provides controls for the user to pick a time or pick a date as ready-to-use
dialogs. Each picker provides controls for selecting each part of the time (hour,
minute, AM/PM) or date (month, day, year). Using these pickers helps ensure that
your users can pick a time or date that is valid, formatted correctly, and adjusted to
the user's locale.
Figure-64
It is recommended that you use DialogFragment to host each time or date picker.
The DialogFragment manages the dialog lifecycle for you and allows you to display
the pickers in different layout configurations, such as in a basic dialog on handsets or
as an embedded part of the layout on large screens.
165
Here's an example:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
Once you've defined a DialogFragment like the one shown above, you can display
the time picker by creating an instance of the DialogFragment and calling show().
For example, here's a button that, when clicked, calls a method to show the dialog:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
166
android:text="@string/pick_time"
android:onClick="showTimePickerDialog" />
When the user clicks this button, the system calls the following method:
This method calls show() on a new instance of the DialogFragment defined above.
The show() method requires an instance of FragmentManager and a unique tag
name for the fragment.
Here's an example:
167
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// 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);
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
For example, here's a button that, when clicked, calls a method to show the dialog:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pick_date"
android:onClick="showDatePickerDialog" />
When the user clicks this button, the system calls the following method:
168
public void showDatePickerDialog(View v) {
DialogFragmentnewFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
This method calls show() on a new instance of the DialogFragment defined above.
The show() method requires an instance of Fragment Manager and a unique tag
name for the fragment.
169
1.12 Check your Progress: Possible Answers
1-a) (A) View 1-b) (B) View Group 1-c) (C) Either (A) or (B)
1-d) (D) TextView 1-e) (B) EditText 1-f) (B) EditText
2-a) (D) Spinner 2-b) on-item-selected 2-c) True
2-d) (C) Date or Time 2-e) False 2-f) True
• https://developer.android.com/reference/android/widget/TextView
• https://developer.android.com/reference/android/widget/EditText
• https://developer.android.com/reference/android/widget/Button
• https://developer.android.com/reference/android/widget/CheckBox
• https://developer.android.com/reference/android/widget/Spinner
1.14 Assignment
1.15 Activity
170