Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
160 views65 pages

Unit, II

Uploaded by

hmoosa.hh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
160 views65 pages

Unit, II

Uploaded by

hmoosa.hh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Android User Interface

• The user interface (UI) for an Android app is


built as a hierarchy of layouts and widgets. The
layouts are ViewGroup objects, containers
that control how their child views are
positioned on the screen. Widgets are View
objects, UI components such as buttons and
text boxes.
Measurements
• When you are specifying the size of an
element on an Android UI, you should
remember the following units of
measurement.
Sr.No Unit & description

1 dp
Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen.

2 sp
Scale-independent pixel. This is similar to dp and is recommended for specifying font
sizes

3 pt
Point. A point is defined to be 1/72 of an inch, based on the physical screen size.

4 px
Pixel. Corresponds to actual pixels on the screen
Device and pixel density independent
measuring UNIT
Screen Densities
Sr.No Density & DPI
1 Low density (ldpi)
120 dpi
2 Medium density (mdpi)
160 dpi
3 High density (hdpi)
240 dpi
4 Extra High density (xhdpi)
320 dpi
INTRODUCING LAYOUTS
• Layout Managers (or simply layouts) are extensions
of the ViewGroup class and are used to position
child Views within your UI.
• Layouts can be nested, letting you create arbitrarily
complex UIs using a combination of layouts.
• The Android SDK includes a number of layout
classes. You can use these, modify them, or create
your own to construct the UI for your Views,
Fragments, and Activities.
• The following list includes some of the most
commonly used layout classes available in the
Android SDK:
– FrameLayout — The simplest of the Layout
Managers, the Frame Layout pins each child view
within its frame. The default position is the top-
left corner, though you can use the gravity attribute
to alter its location.
– LinearLayout — A Linear Layout aligns each
child View in either a vertical or a horizontal line.
A vertical layout has a column of Views, whereas a
horizontal layout has a row of Views.
• RelativeLayout — One of the most flexible of
the native layouts, the Relative Layout lets you
define the positions of each child View relative
to the others and to the screen boundaries.
• GridLayout — Introduced in Android 4.0 (API
level 14), the Grid Layout uses a rectangular
grid of infinitely thin lines to lay out Views in a
series of rows and columns. The Grid Layout is
incredibly flexible and can be used to greatly
simplify layouts and reduce or eliminate the
complex nesting often required to construct
UIs using the layouts described above.
Defining Layouts
• The preferred way to define a layout is by
using XML external resources.
• Each layout XML must contain a single root
element. This root node can contain as many
nested layouts and Views as necessary to
construct an arbitrarily complex UI.
• The following snippet shows a simple layout
that places a TextView above an EditText
control using a vertical LinearLayout.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”Enter Text Below”
/>
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”Text Goes Here!”
/>
</LinearLayout>
Using Layouts to Create Device
Independent User Interfaces
• Using a Linear Layout: The Linear Layout is one of
the simplest layout classes. It allows you to create
simple UIs (or UI elements) that align a sequence
of child Views in either a vertical or a horizontal
line.
• The simplicity of the Linear Layout makes it easy to
use but limits its flexibility. In most cases you will
use Linear Layouts to construct UI elements that
will be nested within other layouts, such as the
Relative Layout.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”>
<LinearLayout
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”
android:padding=”5dp”>
<Button
android:text=”@string/cancel_button_text”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_weight=”1”/>
<Button
android:text=”@string/ok_button_text”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_weight=”1”/>
</LinearLayout>
<ListView
android:layout_width=”match_parent”
android:layout_height=”match_parent”/>
</LinearLayout>
Using a Relative Layout
• The Relative Layout provides a great deal of
flexibility for your layouts, allowing you to
define the position of each element within the
layout in terms of its parent and the other
Views.
• <?xml version=”1.0” encoding=”utf-8”?>
• <RelativeLayout
• xmlns:android=”http://schemas.android.com/apk/res/android”
• android:layout_width=”match_parent”
• android:layout_height=”match_parent”>
• <LinearLayout
• android:id=”@+id/button_bar”
• android:layout_alignParentBottom=”true”
• android:layout_width=”fill_parent”
• android:layout_height=”wrap_content”
• android:orientation=”horizontal”
• android:padding=”5dp”>
• <Button
• android:text=”@string/cancel_button_text”
• android:layout_width=”fill_parent”
• android:layout_height=”wrap_content”
• android:layout_weight=”1”/>
• <Button
• android:text=”@string/ok_button_text”
• android:layout_width=”fill_parent”
• android:layout_height=”wrap_content”
• android:layout_weight=”1”/>
• </LinearLayout>
• <ListView
• android:layout_above=”@id/button_bar”
• android:layout_alignParentLeft=”true”
• android:layout_width=”match_parent”
• android:layout_height=”match_parent”>
• </ListView>
• </RelativeLayout>
Using a Grid Layout
• The Grid Layout was introduced in Android 3.0
(API level 11) and provides the most flexibility of
any of the Layout Managers.
• The Grid Layout uses an arbitrary grid to position
Views. By using row and column spanning, the
Space View, and Gravity attributes, you can
create complex without resorting to the often
complex nesting required to construct UIs using
the Relative Layout described previously.
• <?xml version=”1.0” encoding=”utf-8”?>
• <GridLayout
• xmlns:android=http://schemas.android.com/apk/res/android
• android:layout_width=”match_parent”
• android:layout_height=”match_parent”
• android:orientation=”vertical”>
• <ListView
• android:background=”#FF444444”
• android:layout_gravity=”fill”>
• </ListView>
• <LinearLayout
• android:layout_gravity=”fill_horizontal”
• android:orientation=”horizontal”
• android:padding=”5dp”>
• <Button
• android:text=”Cancel”
• android:layout_width=”fill_parent”
• android:layout_height=”wrap_content”
• android:layout_weight=”1”/>
• <Button
• android:text=”OK”
• android:layout_width=”fill_parent”
• android:layout_height=”wrap_content”
• android:layout_weight=”1”/>
• </LinearLayout>
• </GridLayout>
Table layout
• Android TableLayout going to be arranged
groups of views into rows and columns. You
will use the <TableRow> element to build a
row in the table. Each row has zero or more
cells; each cell can hold one View object.
• TableLayout containers do not display border
lines for their rows, columns, or cells.
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/
android" android:layout_width="fill_parent"
android:layout_height="fill_parent"> <TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"> <TextView
android:text="Time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" /> <TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textClock"
android:layout_column="2" /> </TableRow>
<TableLayout>
User Interface (UI) Components
• Input controls are the interactive components
in your app's user interface. Android provides
a wide variety of controls you can use in your
UI, such as buttons, text fields, seek bars,
check box, zoom buttons, toggle buttons, and
many more.
• A View is an object that draws something on
the screen that the user can interact with and
a ViewGroup is an object that holds other
View (and ViewGroup) objects in order to
define the layout of the user interface.
• Editable and non-editable TextViews:
– TextView: TextView is a UI Component that
displays the text to the user on their Display
Screen. There are various attributes to describe
the TextView some of them are named below:
• Android: id – it is a unique id for the control.
• Android: width – It displays the exact width of the
TextView.
• Android: height – It displays the exact height of the
TextView.
• Android:textColor – It set the color of the text.
• Android: gravity – It is to align the TextView.
• EditText:EditText is a predefined subclass of
TextView that includes rich editing capabilities.

Sr.No Attribute & Description


1 android:autoText
If set, specifies that this TextView has a textual input
method and automatically corrects some common
spelling errors.

2 android:drawableBottom
This is the drawable to be drawn below the text.

3 android:drawableRight
This is the drawable to be drawn to the right of the
text.

4 android:editable
If set, specifies that this TextView has an input method.

5 android:text
This is the Text to display.
• Button:A Button is a Push-button which can be
pressed, or clicked, by the user to perform an
action.
Sr.No Attribute & Description
1 android:autoText
If set, specifies that this TextView has a textual input
method and automatically corrects some common
spelling errors.

2 android:drawableBottom
This is the drawable to be drawn below the text.

3 android:drawableRight
This is the drawable to be drawn to the right of the text.

4 android:editable
If set, specifies that this TextView has an input method.

5 android:text
This is the Text to display.
• Radio Button: A RadioButton has two states: either
checked or unchecked.This allows the user to select
one option from a set.
• Toggle Buttons: A ToggleButton displays
checked/unchecked states as a button. It is basically
an on/off button with a light indicator.
Sr.No. Attribute & Description
1 android:disabledAlpha
This is the alpha to apply to
the indicator when
disabled.
2 android:textOff
This is the text for the
button when it is not
checked.
3 android:textOn
This is the text for the
button when it is checked.
• Checkboxes:A CheckBox is an on/off switch that can
be toggled by the user. You should use check-boxes
when presenting users with a group of selectable
options that are not mutually exclusive.
Sr.No Attribute & Description
android:autoText
If set, specifies that this TextView has a textual input
method and automatically corrects some common
spelling errors.
1

android:drawableBottom
2 This is the drawable to be drawn below the text.

android:drawableRight
This is the drawable to be drawn to the right of the
3 text.

android:editable
If set, specifies that this TextView has an input
4 method.

android:text
5 This is the Text to display.
• Spinner: Spinner allows you to select an item
from a drop down menu.
• For example. When you are using Gmail
application you would get drop down menu as
shown below, you need to select an item from
a drop down menu.
• AlertDialog: Alert Dialog Box is a UI that gives
the users an Alert or Warning of something. It
appears on the screen in a small window.
Once it comes, the user needs to decide or
choose an option that it shows.

For example, when you enter the wrong


password for email id.
• Time Picker:Android Time Picker allows you to
select the time of day in either 24 hour or
AM/PM mode. The time consists of hours,
minutes and clock format. Android provides
this functionality through TimePicker class.
• Date Picker: Android Date Picker allows you to
select the date consisting of day, month and
year in your custom user interface. For this
functionality android provides DatePicker and
DatePickerDialog components.
Event Handling-Handling clicks or changes
of various UI components
• Event handling comes with Event and
Handling. The event here is nothing but an
Action. Handling here means managing. In the
whole Android Event Handling, all we do is
manage the actions.
• These actions are related to the user’s
interaction. These Events collect data about
the user’s interaction using interactive
components.
• For example, when you click on some button,
onClick() is invoked. All the events in Android
are stored in a Queue using First In First Out
(FIFO) scheduling.
• To include the Event Handler in your
application, you should know the following
three concepts:

– Event Listeners
– Event Handlers
– Event Listener Registration
• 1. Event Listeners: An event listener is an
interface in the View class of Android. It has a
single callback method. This method will be
called when the View that is registered with
the Listener is activated by the user’s action.
• Following are some of the important Event
Listeners:
Event Listeners Event listener Description

This event occurs when the user clicks


on an item on the screen in touch more
onClick()
or focuses on an item using a trackball
or navigation-keys.

This event occurs when a user clicks on


onLongClick() an item or screen for more than 1
second.
This event occurs when a user
onFocusChange() navigates away from an item that was
on focus.
This event occurs when a user focuses
onKey()
and clicks on an item.

This event occurs when a user touches


onTouch() a particular range of an item with
gestures or simple touch or tap.

This event occurs when a Context Menu


onCreateContextMenu()
is built.
It occurs when a user clicks or selects
onMenuItemClick()
an item from a menu.
• 2. Event Handlers
– Event handles are the actual methods that have
the action that is to be taken. After an event has
happened and event listeners are registered,
event listeners call Event Handler. These are useful
to define some callback methods.

– Following are some of the important Event


Handlers:
Event Handler Event Handler Description
The system invokes this method
onKeyUp()
when a new key event occurs.
The system invokes this method
onKeyDown()
when a key down event occurs.
The system invokes this method
onTrackballEvent() when a trackball motion event
occurs.
The system invokes this method
onTouchEvent()
when some touch event occurs.
The system invokes this method
onFocusChange() when an item gets into focus or
loses focus.
• 3. Event Listener Registration
– Event Registration is the process in which Event
Listeners are registered with Event Handlers. This
is important as Handler will work only after the
Listener fires an Event.

– Android Event Listener registration can be done in


the following three ways:

• The first method to register event listeners is by directly


mentioning them in activity_main.xml.
• We can also register event listeners by using Activity
class that implements a listener interface.
• The last method is by using an Anonymous class.
Touch mode

• While a user interacts with the device they roll the


screen over. Therefore it’s necessary to focus on the
items that are actionable. In the devices with touch
functionality, and the user begins interacting with it
then it is not important to give focus on touchable
items. This mode of interaction is “Touch Mode”.
• Once a user touches the screen, the device enters in
touch mode and then onwards the actionable icons
and buttons are kept on focus like – navigation
button or home button.
Handling Focus
• The framework handles the focus movement according to
user input. Handling the focus includes adding and
removing the focus according to the user input
movements. Focus changes with the help of Views. You
can check if the View is set to be in focusable mode or not
using isFocusable(). And we can also change the focus
mode by using setFocusable().

• We can set the focus of view in touch mode as well, using


setFocusInTouchMode(). To check if a view allows focus in
touch mode use isFocusableInTouchMode().
Fragments
• Android Fragment is the part of activity, it is
also known as sub-activity. There can be more
than one fragment in an activity. Fragments
represent multiple screen inside one activity.
• A Fragment is a piece of an activity which
enable more modular activity design. It will
not be wrong if we say, a fragment is a kind of
sub-activity.
Creating fragments,
• Extend the Fragment class to create a new Fragment,
(optionally) defining the UI and implementing the
functionality it encapsulates.
• It is possible to create a Fragment that doesn’t include
a UI but instead provides background behavior for an
Activity.
• Unlike Activities, Fragments don’t need to be
registered in your manifest. This is because Fragments
can exist only when embedded into an Activity, with
their lifecycles dependent on that of the Activity to
which they’ve been added.
Lifecycle of fragments
• The lifecycle events of a Fragment mirror
those of its parent Activity; however, after the
containing Activity is in its active resumed
state adding or removing a Fragment will
affect its lifecycle independently.
Android Fragment Lifecycle Methods
No. Method Description
1) onAttach(Activity) it is called only once when it is attached
with activity.

2) onCreate(Bundle) It is used to initialize the fragment.

3) onCreateView(LayoutInflater, ViewGroup, creates and returns view hierarchy.


Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of


onCreate() method.

5) onViewStateRestored(Bundle) It provides information to the fragment


that all the saved state of fragment view
hierarchy has been restored.

6) onStart() makes the fragment visible.


7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no


longer interactive.

9) onStop() is called when fragment is no


longer visible.

10) onDestroyView() allows the fragment to clean up


resources.

11) onDestroy() allows the fragment to do final


clean up of fragment state.

12) onDetach() It is called immediately prior to


the fragment no longer being
associated with its activity.
Fragment example
Fragment States
• Fragment state transitions are closely related to the
corresponding Activity state transitions.
• Like Activities, Fragments are active when they
belong to an Activity that is focused and in the
foreground.
• When an Activity is paused or stopped, the
Fragments it contains are also paused and stopped,
and the Fragments contained by an inactive Activity
are also inactive.
• When an Activity is finally destroyed, each Fragment
it contains is likewise destroyed.
• While Activities and their Fragments are
tightly bound, one of the advantages of using
Fragments to compose your Activity’s UI is the
flexibility to dynamically add or remove
Fragments from an active Activity.
• As a result, each Fragment can progress
through its full, visible, and active lifecycle
several times within the active lifetime of its
parent Activity.
Adding fragments to Activity
• The simplest way to add a Fragment to an
Activity is by including it within the Activity’s
layout using the fragment tag
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”horizontal”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<fragment android:name=”com.paad.weatherstation.MyListFragment”
android:id=”@+id/my_list_fragment”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_weight=”1”
/>
<fragment android:name=”com.paad.weatherstation.DetailsFragment”
android:id=”@+id/details_fragment”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_weight=”3”
/>
</LinearLayout>
adding, removing and replacing fragments
with fragment transactions
• When adding a new UI Fragment, specify the
Fragment instance to add, along with the
container View into which the Fragment will
be placed.
• Optionally, you can specify a tag that can later
be used to find the Fragment by using the
findFragmentByTag method:
• FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
• fragmentTransaction.add(R.id.ui_container,
new MyListFragment());
• fragmentTransaction.commit();
• To remove a Fragment, you first need to find a
reference to it, usually using either the
Fragment Manager’s findFragmentById or
findFragmentByTag methods.
• Then pass the found Fragment instance as a
parameter to the remove method of a
Fragment Transaction:
• FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
• Fragment fragment =
fragmentManager.findFragmentById(R.id.detai
ls_fragment);
• fragmentTransaction.remove(fragment);
• fragmentTransaction.commit();
• You can also replace one Fragment with
another.
• Using the replace method, specify the
containerID containing the Fragment to be
replaced, the Fragment with which to replace
it, and (optionally) a tag to identify the newly
inserted Fragment.
• FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
• fragmentTransaction.replace(R.id.details_frag
ment,new DetailFragment(selected_index));
• fragmentTransaction.commit();
Interfacing between fragments
and Activities
• Use the getActivity method within any Fragment to
return a reference to the Activity within which it’s
embedded
• This is particularly useful for finding the current
Context, accessing other Fragments using the
Fragment Manager, and finding Views within the
Activity’s View hierarchy.
• TextView textView =
(TextView)getActivity().findViewById(R.id.textview)
;
• Where your Fragment needs to share events
with its host Activity, it’s good practice to
create a callback interface within the
Fragment that a host Activity must implement.
Multi-screen Activities
• Two apps running side-by-side in split-screen
mode.
• The user can switch into multi-window mode
in the following ways:
– If the user opens the Overview screen and
performs a long press on an activity title, they can
drag that activity to a highlighted portion of the
screen to put the activity in multi-window mode.
• If the user performs a long press on the
Overview button, the device puts the current
activity in multi-window mode, and opens the
Overview screen to let the user choose
another activity to share the screen.
• Users can drag and drop data from one
activity to another while the activities are
sharing the screen.
• Split Screen introduced in Android Nougat
implemented.
• Set this attribute in your manifest's or element to
enable or disable multi-window display:
• android:resizeableActivity=["true" | "false"]
• If this attribute is set to true, the activity can be
launched in split-screen and freeform modes.
• If the attribute is set to false, the activity does not
support multi-window mode.
• If this value is false, and the user attempts to
launch the activity in multi-window mode, the
activity takes over the full screen.

You might also like