0% found this document useful (0 votes)
4 views51 pages

Unit 5

This document outlines the design of user interfaces in Android applications, focusing on various UI components such as TextView, Button, ImageButton, EditText, CheckBox, and more. It also covers advanced topics like RecyclerView for displaying long lists, specialized fragments, and multimedia handling with VideoView and MediaController. Additionally, it explains the use of picker views for selecting dates and times, along with the implementation of animations and graphics.

Uploaded by

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

Unit 5

This document outlines the design of user interfaces in Android applications, focusing on various UI components such as TextView, Button, ImageButton, EditText, CheckBox, and more. It also covers advanced topics like RecyclerView for displaying long lists, specialized fragments, and multimedia handling with VideoView and MediaController. Additionally, it explains the use of picker views for selecting dates and times, along with the implementation of animations and graphics.

Uploaded by

work.sohamp
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PUNE INSTITUTE OF COMPUTER TECHNOLOGY PUNE

Android Development
Unit 5
Designing user Interface with widgets

Department of Electronics and Telecommunication Engineering​


[Link]. [Link]
Email Id: pbtathe@[Link]
CO3:
• Design android applications involving data storage in
databases.

[Link]
Syllabus
Using Basic Views:
[Link] View, [Link], [Link], [Link], [Link], [Link], [Link],
[Link] Button, and [Link] Group Views,[Link] View,
[Link]
View-Using Picker Views, Using RecyclerView to Display Long Lists,
Understanding Specialized Fragments,
Displaying Pictures and Menus,
Video View Multimedia,
Animation and Graphics: Playing Audio, Playing Video, Rotate Animation, Fade In /Fade Out
Animation, Zoom Animation, Scale Animation, 2D and 3D Graphics.

[Link]
1. TextView
TextView is a UI Component that displays the text to the user on their Display
Screen.

For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= "[Link]


<TextView
//attributes to describe it
/>
</LinearLayout>

[Link]
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.

[Link]
• 2. Button
This is a UI that is used to perform some action as soon as the user clicks on it.
XML file:
For this, we declare it in the layout tag as follows:

<Linear Layout xmls:android= ”[Link]


<Button
//attributes
/>
</LinearLayout>

[Link]
3. ImageButton
It is the same as a Button but it’s used to display an image on the button to perform an Action. In this, we need to
give the source of the image so that the system can load it.
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”[Link]

<ImageButton
//other attributes...
android:src= “@drawable/add_icon”/>

</LinearLayout>

[Link]
[Link]
EditText is a user interface control that allows the users to enter some
text.
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”[Link]
<EditText
//attributes
>
</LinearLayout>

[Link]
5. CheckBox
A CheckBox is the UI control that has two states that are either checked or unchecked. If we have a
group of CheckBox, we can select as many as we want, unlike RadioGroup.
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”[Link]
<CheckBox
android:checked="true"
android:text="CheckBox"
// other attributes
/>
</LinearLayout>

[Link]
[Link]
• In Android, a switch is a two-state UI element that holds either ON or OFF state. ON
generally means Yes and OFF means No. By default, a switch is in the OFF state. A
user can change its state many times.

[Link]
7. ToggleButton
The toggle button displays the ON/OFF states of a button with a light indicator.
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”[Link]
<ToggleButton
//attributes
android:checked="true"
android:textOff="OFF"
android:textOn="ON"/>
</LinearLayout>

[Link]
8. RadioButton
Radio button in Android is the one that has only two possible states, that are either checked or
unchecked. Initially, it is in the unchecked state, once it’s checked it can’t be unchecked.
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”[Link]
<RadioButton
android:text="Radio button"
android:checked="true"/>
</LinearLayout>

[Link]
9. RadioGroup
It’s a group of Radio buttons that are alike. In this, only one of all the buttons can be chosen.
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android= ”[Link]
RadioGroup android:orientation="vertical">
<RadioButton android:text="Radio Button 1"/>
<RadioButton android:text="Radio Button 2"/>
<RadioButton android:text="Radio Button 3"/>
</RadioGroup>

</LinearLayout>

[Link]
[Link]
In Android, we have a progress bar that shows the progress of some action that is happening like pasting a
file to some location. A progress bar can be in two modes:
Determinate Mode:
In this, the progress is shown with the percent of action completed. Also, the time to be taken is already
determined.
Indeterminate Mode:
In this, there is no idea of when the task would be completed, therefore, it functions continuously.
XML file:
For this, we declare it in the layout tag as follows:
<Linear Layout xmls:android=”[Link]
<ProgressBar
// attributes, here we define the speed, layout, id, etc.
/>
</LinearLayout>
[Link]
[Link]
• AutoCompleteTextView is an extension of EditText. In this UI element, the user is
provided with a few suggestions of some values/texts. The value can be chosen by the
user while filling AutoCompleteTextView.

[Link]
Picker Views
• 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). For this functionality android provides DatePicker
and DatePickerDialog [Link] this we’ll demonstrate the use of a Date Picker
and Timer Picker Dialog in our android application.

• These components are used to select date and time in a customised user interface. We
will use DatePickerDialog and TimePickerDialog classes with Calendar class in our
android application code to achieve this.

[Link]
DatePickerDialog and TimePickerDialog classes have onDateSetListener() and onTimeSetListener()
callback methods respectively. These callback methods are invoked when the user is done with filling
the date and time respectively.
Date Picker
The DatePickerDialog class consists of a 5 argument constructor with the parameters listed below.
1. Context: It requires the application context.
2. CallBack Function: onDateSet() is invoked when the user sets the date with the following parameters:
int year : It will be store the current selected year from the dialog.
int monthOfYear : It will be store the current selected month from the dialog.
int dayOfMonth : It will be store the current selected day from the dialog.
3. int mYear : It shows the the current year that’s visible when the dialog pops up.
4. int mMonth : It shows the the current month that’s visible when the dialog pops up.
5. int mDay : It shows the the current day that’s visible when the dialog pops up.
[Link]
Time Picker
The TimePickerDialog class consists of a 5 argument constructor with the parameters
listed below.

[Link]: It requires the apppcation context.


[Link] Function: onTimeSep) is invoked when the user sets the time with the
following parameters:
int hourOfDay : It will be store the current selected hour of the day from the dialog.
int minute : It will be store the current selected minute from the dialog.
3. int mHours : It shows the the current Hour that’s visible when the dialog pops up.
4. int mMinute : It shows the the current minute that’s visible when the dialog pops up.
5. boolean false : If its set to false it will show the time in 24 hour format else not.

[Link]
A picker view can be defined as the view that shows a spinning wheel or slot machine to
display one or more set of values so that the user can spin the wheel to select one. It is an
instance of UIPickerView class which inherits UIView.

class UIPickerView : UIView


As the name suggests, the picker view allows the user to pick an item from the set of
multiple items. PickerView can display one or multiple sets where each set is known as a
component. Each component displays a series of indexed rows representing the selectable
items. The user can select the items by rotating the wheels.

Adding PickerView to iOS application


Search for the UIPickerView in the object library and drag the result to the storyboard.
Define the auto layout rules for the pickerview to govern its position and size on different
screen devices.
Implement UIPickerViewDelegate and UIPickerViewDataSource protocol to govern the data
and the appearance of PickerView.

[Link]
Recycler view to display long list
• Recycler View makes it easy to efficiently display large sets of data.
• User supply the data and define how each item looks, and the RecyclerView library
dynamically creates the elements when they're needed.
• As the name implies, Recycler View recycles those individual elements.
• When an item scrolls off the screen, Recycler View doesn't destroy its view. Instead,
Recycler View reuses the view for new items that have scrolled onscreen.
• Recycler View improves performance and responsiveness od apps, and it reduces
power consumption.

[Link]
• Several classes work together to build your dynamic list.
• RecyclerView is the ViewGroup that contains the views corresponding to your data. It's
a view itself, so you add RecyclerView to your layout the way you would add any other
UI element.
• Each individual element in the list is defined by a view holder object. When the view
holder is created, it doesn't have any data associated with it. After the view holder is
created, the RecyclerView binds it to its data. You define the view holder by extending
[Link].
• The RecyclerView requests views, and binds the views to their data, by calling methods
in the adapter. You define the adapter by extending [Link].
• The layout manager arranges the individual elements in your list. You can use one of
the layout managers provided by the RecyclerView library, or you can define your own.
Layout managers are all based on the library's LayoutManager abstract class.

[Link]
How RecyclerView Works?
RecyclerView is a ViewGroup that contains Views corresponding to your data. It itself a View
so, it is added to the layout file as any other UI element is added.
ViewHolder Object is used to define each individual element in the list. View holder does not
contain anything when it created, RecyclerView binds data to it. ViewHolder is defined by
extending [Link].
Adapters are used to bind data to the Views. RecyclerView request views, and binds the views
to their data, by calling methods in the adapter. The adapter can be defined by extending
[Link].
LayoutManager arranges the individual elements in the list. It contains the reference of all views
that are filled by the data of the entry.
LayoutManager class of RecyclerView provide three types of built-in LayoutManagers

LinearLayoutManager: It is used for displaying Horizontal and Vertical List


GridLayoutManager: It is used for displaying items in the forms of grids
StaggeredGridLayoutManager: It is used for displaying items in form of staggered grids
[Link]
Specialized Fragments
The Fragments API provides other subclasses that encapsulate some of the more common
functionality found in applications. These subclasses are
ListFragment – This Fragment is used to display a list of items bound to a datasource
such as an array or a cursor.
DialogFragment – This Fragment is used as a wrapper around a dialog. The Fragment will
display the dialog on top of its Activity.
PreferenceFragment – This Fragment is used to show Preference objects as lists.
The ListFragment
The ListFragment is very similar in concept and functionality to the ListActivity; it is a
wrapper that hosts a ListView in a Fragment.
[Link]
DialogFragment
The DialogFragment is a Fragment that is used to display a dialog object inside of a Fragment that will
float on top of the Activity's window. It is meant to replace the managed dialog APIs (starting in
Android 3.0).
A DialogFragment ensures that the state between the Fragment and the dialog remain consistent. All
interactions and control of the dialog object should happen through the DialogFragment API, and not be
made with direct calls on the dialog object. The DialogFragment API provides each instance with a
Show() method that is used to display a Fragment. There are two ways to get rid of a Fragment:
Call [Link]() on the DialogFragment instance.
Display another DialogFragment.
To create a DialogFragment, a class inherits from [Link], and then overrides one
of the following two methods:
OnCreateView – This creates and returns a view.
OnCreateDialog – This creates a custom dialog. It is typically used to show an AlertDialog. When
overriding this method, it is not necessary to override OnCreateView . [Link]
• PreferenceFragment
• To help manage preferences, the Fragments API provides the
PreferenceFragment subclass. The PreferenceFragment is similar to the
PreferenceActivity – it will show a hierarchy of preferences to the user in a
Fragment. As the user interacts with the preferences, they will be
automatically saved to SharedPreferences. In Android 3.0 or higher
applications, use the PreferenceFragment to deal with preferences in
applications.

[Link]
Displaying pictures and menus
In Android,
[Link] Gallery is a view that can show items(images) in a center-locked, horizontal
scrolling list, and hence the user can able to select a view, and then the user-selected view
will be shown in the center of the Horizontal list.
“N” number of items can be added by using the Adapter.
The adapter is a bridging component between the UI component and the data source.
[Link] ImageView
Android ImageView is a class. This class can load images from various sources. It
displays an image as icon.

[Link]
• Important Methods of Gallery View in Android

Methods Description
To set the duration for how long a transition animation should
run
setAnimationDuration(int) (in milliseconds) whenever there is a change in layout.
This can be set in xml also via
android:animationDuration=”3000″
To set the spacing between items in a Gallery. This can be set
setSpacing(int) in xml
also via android:spacing=”5dp”
To set the alpha on the items that are not selected. This can be
setUnselectedAlpha(float) set in xml
also via android:unselectedAlpha=”0.25″
[Link]
Video view multimedia
Android Video Player Example
By the help of MediaController and VideoView classes, we can play the video files in
android.
MediaController class
The [Link] is a view that contains media controls like
play/pause, previous, next, fast-forward, rewind etc.
VideoView class
The class provides methods to play and control the video player.
[Link]

[Link]
Method Description
PublicvoidsetMediaController(MediaCont
sets the media controller to the video view.
roller controller)

public void setVideoURI (Uri uri) sets the URI of the video file.
public void start() starts the video view.
public void stopPlayback() stops the playback.
public void pause() pauses the playback.
public void suspend() suspends the playback.
public void resume() resumes the playback.
public void seekTo(int millis) seeks to specified time in miliseconds.
Playing Audio
Adding audio clip to android application is a simple task as it also add some further functionality. Here
is a step by step on how to play music when App will start.
Adding Audio to app in Android Studio:
Step 1: Open the android studio with the project in which you want to add-on audio clip/media file.
Step 2: Create a raw folder.
Step 3: Add media file to raw folder by simply copy and paste that to raw folder.
adding-media-in-android-studio
Step 4: Here we added a media file “ring.mp3” . Now open the Java File of desired activity, here we are
adding audio in MainActivity.
Step 5: Further add this code
MediaPlayer ring= [Link]([Link],[Link]);
[Link]();
Step 6: Now run the App and your music will play when App will start.

[Link]
• We can play and control the audio files in android by the help of MediaPlayer class.
• The [Link] class is used to control the audio or video files
Method Description
public void setDataSource(String path) sets the data source (file path or http url) to use.
public void prepare() prepares the player for playback synchronously.
public void start() it starts or resumes the playback.
public void stop() it stops the playback.
public void pause() it pauses the playback.
public boolean isPlaying() checks if media player is playing.
public void seekTo(int millis) seeks to specified time in miliseconds.
public void setLooping(boolean looping) sets the player for looping or non-looping.
public boolean isLooping() checks if the player is looping or non-looping.
public void selectTrack(int index) it selects a track for the specified index.
public int getCurrentPosition() returns the current playback position.
public int getDuration() returns duration of the file.
public void setVolume(float leftVolume,float rightVolume) sets the volume on this player.
[Link]
Playing Video
By the help of MediaController and VideoView classes, we can play the video files in
android.
MediaController class
The [Link] is a view that contains media controls like
play/pause, previous, next, fast-forward, rewind etc.
VideoView class
The [Link] class provides methods to play and control the video
player.

[Link]
commonly used methods of VideoView class are as follows:

Method Description
public void setMediaController(MediaController controller) sets the media controller to the video view.

public void setVideoURI (Uri uri) sets the URI of the video file.

public void start() starts the video view.

public void stopPlayback() stops the playback.

public void pause() pauses the playback.

public void suspend() suspends the playback.

public void resume() resumes the playback.

public void seekTo(int millis) seeks to specified time in miliseconds.


Android Animation
• Android Animation is used to give the UI a rich look and feel.
• Animations in android apps can be performed through XML or android code.
• Animation in android apps is the process of creating motion and shape change.

Different types of animations are


[Link] In Animation [Link] Animation
[Link] Out Animation [Link] Animation
[Link] Fading Animation [Link] Up Animation
[Link] Down Animation
[Link] Animation
[Link] Animation
[Link] In Animation [Link] Animation
[Link] Out Animation [Link] Animation
• We create a resource directory under the res folder names anim to
keep all the xml files containing the animation logic.
<?xml version="1.0" encoding="utf-8"?>
<scale
xmlns:android="[Link]
"

android:interpolator="@android:anim/accelerate_decelerate_i
nterpolator"
android:duration="300"
android:fillAfter="true"
android:fromXScale="0.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />

[Link]
android:interpolator : It is the rate of change in animation. We can define our own interpolators using the time as the
constraint. In the above xml code an inbuilt interpolator is assigned

android:duration : Duration of the animation in which the animation should complete. It is 300ms here. This is generally
the ideal duration to show the transition on the screen. The start and end of the animation are set using:

android:fromTRANSFORMATION
android:toTRANSFORMATION
TRANSFORMATION : is the transformation that we want to specify. In our case we start with an x and y scale of 0 and
end with an x and y scale of 1

android:fillAfter : property specifies whether the view should be visible or hidden at the end of the animation. We’ve set
it visible in the above code. If it sets to false, the element changes to its previous state after the animation

android:startOffset : It is the waiting time before an animation starts. This property is mainly used to perform multiple
animations in a sequential manner

android:repeatMode : This is useful when you want the animation to be repeat

android:repeatCount : This defines number of repetitions on animation. If we set this value to infinite then animation
will repeat infinite times
Setting the Animation Listeners
• This is only needed if we wish to listen to events like start, end or
repeat. For this the activity must implement AnimationListener and
the following methods need to overridden.

• onAnimationStart : This will be triggered once the animation started


• onAnimationEnd : This will be triggered once the animation is over
• onAnimationRepeat : This will be triggered if the animation repeats

[Link]
Fade In Animation
fade_in.xml

<set xmlns:android="[Link]
android:fillAfter="true" >
<alpha
android:duration="1000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
Here alpha references the opacity of an object. An object with lower alpha values is more
transparent, while an object with higher alpha values is less transparent, more opaque.
Fade in animation is nothing but increasing alpha value from 0 to 1.

[Link]
Fade Out Animation
fade_out.xml

<set xmlns:android="[Link]
android:fillAfter="true" >
<alpha
android:duration="1000"
android:fromAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
</set>

Fade out android animation is exactly opposite to fade in, where we need to decrease the
alpha value from 1 to 0.

[Link]
Zoom In Animation
zoom_in.xml
<set xmlns:android="[Link]
android:fillAfter="true" >
<scale
xmlns:android="[Link]
android:duration="1000"
android:fromXScale="1"
android:fromYScale="1"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="3"
android:toYScale="3" >
</scale>
</set>
We use pivotX="50%" and pivotY="50%" to perform zoom from the centre of the element.
[Link]
Zoom out Animation
zoom_out.xml

<set xmlns:android="[Link]
android:fillAfter="true" >
<scale
xmlns:android="[Link]
android:duration="1000"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.5"
android:toYScale="0.5" >
</scale>
</set>
Notice that android:from and android:to are opposite in zoom_in.xml and zoom_out.xml.

[Link]
Rotate Animation
[Link]
<set xmlns:android="[Link]
<rotate android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="600"
android:repeatMode="restart"
android:repeatCount="infinite"
android:interpolator="@android:anim/cycle_interpolator"/>
</set>
A from/toDegrees tag is used here to specify the degrees and a cyclic interpolator is used.

[Link]
Scale animation
Added in API level 1

public ScaleAnimation (float fromX,


float toX,
float fromY,
float toY,
int pivotXType,
float pivotXValue,
int pivotYType,
float pivotYValue)

[Link]
Parameters
fromX float: Horizontal scaling factor to apply at the start of the animation
toX float: Horizontal scaling factor to apply at the end of the animation
fromY float: Vertical scaling factor to apply at the start of the animation
toY float: Vertical scaling factor to apply at the end of the animation
pivotXType int: Specifies how pivotXValue should be interpreted. One of [Link],
Animation.RELATIVE_TO_SELF, or Animation.RELATIVE_TO_PARENT.
pivotXValue float: The X coordinate of the point about which the object is being scaled, specified as an
absolute number where 0 is the left edge. (This point remains fixed while the object changes
size.) This value can either be an absolute number if pivotXType is ABSOLUTE, or a percentage
(where 1.0 is 100%) otherwise.
pivotYType int: Specifies how pivotYValue should be interpreted. One of [Link],
Animation.RELATIVE_TO_SELF, or Animation.RELATIVE_TO_PARENT.
pivotYValue float: The Y coordinate of the point about which the object is being scaled, specified as an
absolute number where 0 is the top edge. (This point remains fixed while the object changes
size.) This value can either be an absolute number if pivotYType is ABSOLUTE, or a percentage
(where 1.0 is 100%) otherwise.
Following are the three animation systems used in Android applications:
1. Property Animation
2. View Animation
3. Drawable Animation

1. Property Animation
Property animation is the preferred method of animation in Android.
This animation is the robust framework which lets you animate any properties of any objects,
view or non-view objects.
The [Link] provides classes which handle property animation.

[Link]
2. View Animation
View Animation is also called as Tween Animation.
The [Link] provides classes which handle view animation.
This animation can be used to animate the content of a view.
It is limited to simple transformation such as moving, re-sizing and rotation, but not its
background color.
a view object.

[Link]
3. Drawable Animation
Drawable animation is implemented using the AnimationDrawable class.
This animation works by displaying a running sequence of 'Drawable' resources that is
images, frame by frame inside

[Link]
2D 3D graphics
• The Android framework offers a variety of graphics rendering APIs for
2D and 3D that interact with manufacturer implementations of
graphics drivers, so it is important to have a good understanding of
how those APIs work at a higher level. This page introduces the
graphics hardware abstraction layer (HAL) upon which those drivers
are built.

• Application developers draw images to the screen in three ways: with


Canvas, OpenGL ES, or Vulkan.

[Link]
2D 3D graphics
Android graphics provides low level graphics tools such as canvases, color, filters, points and rectangles which handle drawing to the screen
directly.
The Android framework provides a set of 2D-DRAWING APIs which allows user to provide own custom graphics onto a canvas or to
modify existing views to customize their look and feel.
There are two ways to draw 2D graphics,
1. Draw your animation into a View object from your layout.
2. Draw your animation directly to a Canvas.
Some of the important methods of Canvas Class are as follows
i) drawText()
ii) drawRoundRect()
iii) drawCircle()
iv) drawRect()
v) drawBitmap()
vi) drawARGB()
You can use these methods in onDraw() method to create your own custom user interface.
Drawing an animation with a View is the best option to draw simple graphics that do not need to change dynamically and are not a part of a
performance-intensive game. It is used when user wants to display a static graphic or predefined animation.
Drawing an animation with a Canvas is better option when your application needs to re-draw itself regularly. For example video games
should be drawing to the Canvas on its own.
[Link]
2D 3D graphics
• Android includes support for high performance 2D and 3D graphics with the Open Graphics
Library (OpenGL®), specifically, the OpenGL ES API. OpenGL is a cross-platform graphics
API that specifies a standard software interface for 3D graphics processing hardware. OpenGL
ES is a flavor of the OpenGL specification intended for embedded devices. Android supports
several versions of the OpenGL ES API:

• OpenGL ES 1.0 and 1.1 - This API specification is supported by Android 1.0 and higher.
• OpenGL ES 2.0 - This API specification is supported by Android 2.2 (API level 8) and higher.
• OpenGL ES 3.0 - This API specification is supported by Android 4.3 (API level 18) and
higher.
• OpenGL ES 3.1 - This API specification is supported by Android 5.0 (API level 21) and
higher.

[Link]
[Link]

You might also like