0% found this document useful (0 votes)
40 views141 pages

Chapter 3 - 4 Notes New

The document outlines the Android app development process, starting from defining an idea and its requirements to prototyping, developing, testing, and publishing the app. It details the steps involved in creating a project in Android Studio, including setting up the user interface, coding, and managing project files and directories. Additionally, it describes the main sections of the Android Studio IDE and the various tool windows that facilitate app development.

Uploaded by

divyamundlik21
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)
40 views141 pages

Chapter 3 - 4 Notes New

The document outlines the Android app development process, starting from defining an idea and its requirements to prototyping, developing, testing, and publishing the app. It details the steps involved in creating a project in Android Studio, including setting up the user interface, coding, and managing project files and directories. Additionally, it describes the main sections of the Android Studio IDE and the various tool windows that facilitate app development.

Uploaded by

divyamundlik21
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
You are on page 1/ 141

Layouts, Views and Resources

3.1.1 The development process :


An Android app project begins with an idea and a definition of the requirements necessary
to realize that idea. As the project progresses, it goes through design, development, and testing.

Fig.3.1.1 The development process

The above diagram is a high-level picture of the development process, with the following steps:
1. Defining the idea and its requirements: Most apps start with an idea of what it should
do,bolstered by market and user research. During this stage the app's requirements are defined.
2. Prototyping the user interface: Use drawings, mock ups and prototypes to show what the user
interface would look like, and how it would work.
3. Developing and testing the app: An app consists of one or more activities. For each activity you
can use Android Studio to do the following, in no particular order:
 Create the layout: Place UI elements on the screen in a layout, and assign string resources
and menu items, using the Extensible Markup Language(XML).
 Write the Java code: Create source code for components and tests, and use testing and
debugging tools.
 Register the activity: Declare the activity in the manifest file.
 Define the build: Use the default build configuration or create custom builds for different
versions of your app.
 Publishing the app: Assemble the final APK (package file) and distribute it through
channels such as the Google Play.

General steps of app development for developing our first app:


1. Creating an Android Studio project.
2. Setting up the User Interface (UI) of the app.
3. Connecting the UI components such as buttons, textboxes, etc. to the Java code.
4. Coding in Java – the actual programming part .
5. Building the project: this means creating the executable (file that actually runs on device or the
emulator). This is not difficult as it sounds; Android Studio does the entire job with a single click
6. Trying the app on an emulator.
7. Running the app on a real Android device (optional).
8. Publishing the app on Google Play (optional).

3.1.2 Creating the project:


1. Start Android Studio by clicking on its icon in the start menu .
2. If you get the Windows Firewall has blocked some features of this program message, as
pictured in the next screenshot, click on Allow access:

PREPARED BY MRS. V.R.SONAR 1


3. Now, you will see the Welcome to Android Studio start menu ,click on Start a new Android
Studio project. You will see the New Project screen pictured next.

4. First, give name to application in the Application name field.


You can choose any name you like for your first application, but just be aware that Android Studio
will soon generate a whole bunch of code and files for us and that the name you choose will be
reflected in them. If you want your code and files to be identical to those that we will be examining
shortly, call your application Hello Android.
5. Next, the Company Domain field. This is where you will enter the details of your company. It is a
convention and very practical (because it is unique) to use the domain name of your company website.
Unlike the application name, using a different company domain will have almost zeroeffect on
the code and files. Choose and enter a company domain name.
6. Now, the Package name field. It has been automatically derived from the previous two fields.
Remember that a package is a collection of the Java classes that are our code files, and our apps can
comprise one or more packages if we wish them to, but they must comprise at least one package.
We can edit the package name by clicking on the edit link, but we have no need to do so here.
7. Finally, in the Project location field, you can accept the default settings or browse to the location
where you would like to store all your Android projects. You have the option to change this for each

PREPARED BY MRS. V.R.SONAR 2


project that you create.

8. Click on the Next button to continue and you will see the Target Android Devices window:

9. Here, we can see that we have the option of developing an application for a phone, tablet, TV, and
wear. Wear is the range of Android-enabled smartwatches. In the preceding screenshot, in the grayed-
out part at the bottom of the window, we can also see that we can develop for Glass, Google's trendy
Android-enabled glasses, although we would need to install additional files to do this. In this book,
we will be developing for phones and tablets, so the already selected option is justwhat we need. The
only other thing we need to choose on this screen is the Minimum SDK. We already know that the
Android SDK is a collection of packages of code that we will be using to develop our apps. Like any
good SDK, the Android SDK is regularly updated, and each time it gets a significant update, the
version number is increased. Simply put, the higher the version number, the newer the features you
get to use; the lower the version number, the more devices our app will work on. For now, the default
setting API 15: Android 4.0.3 (IceCreamSandwich) will give us lotsof great features and at least 90%
compatibility with the Android devices that are currently in use.
10. Click on the Next button. Now we can see the Add an activity to Mobile window:

PREPARED BY MRS. V.R.SONAR 3


11. An Activity class is a special Java class and every Android app must have at least one. It is the
part of the code where our app will start when it is launched by the user, and this also handles any
interaction with the user. The options on this screen provide different ready-made templates of the
Activity class code in order to give programmers a fast start when creating various types of apps.
As we are starting from scratch, the most appropriate option for us is Blank Activity. Make sure that
Blank Activity is selected by clicking on it and then clicking on Next. Now, take a look at the
Customize the Activity window:

12. The Customize the Activity window gives us four things. It is perfectly possible to leave them
all at their default settings. Activity Name is the name of the class that will contain our code. Name
the activity MyActivity.
13. The next field is Layout Name. Android UI layouts are usually defined in a separate XML text
file, not with our Java code. The layout name is what this file will be called. Name the layout
my_layout.
14. The next field is Title. This is different than the Activity Name field and will be used by Android
on the device's screen as the name of the app. Name the title My App.
15. Finally the Menu Resource Name. Menus are the pop-up options that you get on Android when
you click on the menu button. They might also be shown on the topmost bar of the app known as the
action bar. This varies depending on the version of Android a device is running. These are considered
to be part of the UI as well and are usually defined in this separate XML file. Name the menu file
my_menu.
PREPARED BY MRS. V.R.SONAR 4
16. Click on the Finish button, and Android Studio will now create a project for us based on our
choices.

Directory and File Structure of an Android Studio Project:


The file structure of an Android project can be viewed in various forms in Android Studio.
The button just at above the left pane (shown by the arrow) is used to open the selection box for
choosing the preferred method of viewing the file hierarchy as shown in Figure The default
file viewer is the ―Android‖ mode.

Figure Switching among different ways of viewing files and folders

When the selection is the ―Android‖ mode, the default files and folders shown in Figure

Figure Default folder and file structure of an Android project


You can use the arrows (shown inside the circle in the figure) for viewing the contents of folders. The
default folders (shown inside the rectangles in Figure ) and their contents are explained as follows:

PREPARED BY MRS. V.R.SONAR 5


1. manifests folder: This folder has the AndroidManifest.xml file inside. This file contains the
configuration parameters of the project such as permissions, services and additional libraries.
2. java folder: The source code files written in Java programming language reside in this folder. You
can see that the java file of the activity named ―MainActivity.java‖ is automatically created in this
folder.
3. res folder: The resource files are contained in this folder. Resources basically mean all the needed
files except the source code. The media, image and layout files residing in the resources folder are
accessed via Java code written in MainActivity.java.

Figure file structure of an Android project


Some of the key files and directory(folders) are as shown in fig.

PREPARED BY MRS. V.R.SONAR 6


Fig: directory structure of an Android project
Let‘s see each folder in detail:
 src - Java source files associated with your project. This includes the Activity "controller"
files as well as your models and helpers.
 res - Resource files associated with your project. All graphics, strings, layouts, and other
resource files are stored in the resource file hierarchy under the res directory.
 res/layout - XML layout files that describe the views and layouts for each activity and for
partial views such as list items.
 res/values - XML files which store various attribute values. These include strings.xml,
dimens.xml, styles.xml, colors.xml, themes.xml, and so on.
 res/drawable - Here we store the various density-independent graphic assets used in our
application.
 res/drawable-hdpi - Series of folders for density specific images to use for various
resolutions.
 res/mipmap - most commonly used for application icons.
The most frequently edited files are:
 res/layout/activity_foo.xml - This file describes the layout of the activity's UI. This means
the placement of every view object on one app screen.
 src/.../FooActivity.java - The Activity "controller" that constructs the activity using the view,
and handles all event handling and view logic for one app screen.
 AndroidManifest.xml - This is the Android application definition file. It contains
information about the Android application such as minimum Android version, permission to

PREPARED BY MRS. V.R.SONAR 7


access Android device capabilities such as internet access permission, ability to use phone
permission, etc.
Other less edited folders include:
 gen - Generated Java code files, this library is for Android internal use only.
 assets - Uncompiled source files associated with your project; Rarely used.
 bin - Resulting application package files associated with your project once it‘s been built.
 libs - Before the introduction of Gradle build system, this directory was used for any
secondary libraries (jars) you might want to link to your app.

3.2 Components of a screen:


3.2.1 Main Sections of the IDE :
Android Studio is a sophisticated tool and it has dozens of properties to make app development
easier. The main sections of Android Studio is as shown in Figure 3.2.1.

Fig. 3.2.1. Basics sections of Android Studio


Section 1. The project files and folders can be viewed from here. In addition, new files can be added
from this pane. We need to double-click on the filenames here to open them in the middle pane. The
project structure will be explained in detail in the next subsection.
Section 2. The opened files can be activated from the tabs located here for viewing in the middle
pane.
Section 3. This is the middle pane. Contents of the active files can be viewed and changed from here.
For the project shown in Figure 3.2.1, the file called ―MainActivity.java‖ is the active tab in Section
2 therefore the middle pane in Section 3 shows the contents of this ―MainActivity.java‖
file.
Section 4. This section is also controlled via tabs. The developer can switch project files, structures,
captures and favourites for viewing in the left pane.
Section 5. The current or previous compilation, building or debugging processes are shown here.
For the snapshot of Figure 3.2.1, it is indicated that the ―Gradle build finished in 14 seconds‖.
Gradle is the build system of Android Studio. Therefore, the message says that the building engine
completed its previous task in 14 seconds.
Section 6. This is the Run button of Android Studio. When we set up the user interface and write
the Java code of a project, we click this button to make the Android Studio build the project (which
means creating the executable file from project files) and then we can run it on an emulator or on a
real device.

3.2.2 The Tool Windows:


In addition to the project view tool window, Android Studio also includes a number of other
windows which, when enabled, are displayed along the bottom and sides of the main window.
The tool window quick access menu can be accessed by hovering the mouse pointer over the
PREPARED BY MRS. V.R.SONAR 8
button located in the far left hand corner of the status bar (Figure 3.2.2) without clicking the mouse
button(pointed by the arrow).

Fig. 3.2.2. The Tool Window of Android Studio


Selecting an item from the quick access menu will cause the corresponding tool window to appear
within the main window. Alternatively, a set of tool window bars can be displayed by clicking on
the quick access menu icon in the status bar. These bars appear along the left, right and bottom
edges of the main window (as indicated by the arrows in Fig3.2.3) and contain buttons for
showing and hiding each of the tool windows. When the tool window bars are displayed,a
second click on the button in the status bar will hide them.

Fig.3.2.3 tool window bars

Clicking on a button will display the corresponding tool window while a second click will hide the
window. Buttons prefixed with a number (for example 1: Project) indicate that the tool window
may also be displayed by pressing the Alt key on the together with the corresponding number. The
location of a button in a tool window bar indicates the side of the window against
PREPARED BY MRS. V.R.SONAR 9
which the window will appear when displayed. These positions can be changed by clicking and
dragging the buttons to different locations in other window tool bars.Each tool window has its own
toolbar along the top edge. The buttons within these toolbars vary from one tool to the next, though
all tool windows contain a settings option, represented by the cogicon,which allows
various aspects of the window to be changed.
Fig.3.2.4 shows the settings menu for the project view tool window(pointed by arrow). Options
are available, for example, to undock a window and to allow it to float outside of the boundaries of
the Android Studio main window and to move and resize the tool panel.

Fig. 3.2.4 settings menu for the project view tool window

All of the windows also include a far right button on the toolbar providing an additional way to
hide the tool window from view. A search of the items within a tool window can be performed
simply by giving that window focus by clicking in it and then typing the search term (for
example the name of a file in the Project tool window). A search box will appear in the window‘s
tool bar and items matching the search highlighted.Android Studio offers a wide range of window
tool windows, the most commonly used of which are as follows:
Project– The project view provides an overview of the file structure that makes up the project
allowing for quick navigation between files. Generally, double clicking on a file in the project
view will cause that file to be loaded into the appropriate editing tool.
Structure–The structure tool provides a high level view of the structure of the source file currently
displayed in the editor. This information includes a list of items such as classes, methods and variables
in the file. Selecting an item from the structure list will take youto that location in the ource file in
the editor window.
Captures–The captures tool window provides access to performance data files that have been
generated by the monitoring tools contained within the Android Monitor tool window.
Favorites–A variety of project items can be added to the favorites list. Right-clicking on a file
in the project view, for example, provides access to an Add to Favorites menu option. Similarly, a
method in a source file can be added as a favourite by right-clicking on it in the Structure tool
window. Anything added to a Favorites list can be accessed through this Favorites tool window.
Build Variants–The build variants tool window provides a quick way to configure different build
targets for the current application project (for example different builds for debugging and release
versions of the application, or multiple builds to target different device categories).

PREPARED BY MRS. V.R.SONAR 10


TODO–As the name suggests , this tool provides a place to review items that have yet to be completed
on the project. Android Studio compiles this list by scanning the source files that make up the
project to look for comments that match specified TODO patterns. These patternscan be reviewed
and changed by selecting the File -> Settings… menu option and navigating to the TODO page
listed under Editor.
Messages–The messages tool window records output from the Gradle build system (Gradle is the
underlying system used by Android Studio for building the various parts of projects into runnable
applications) and can be useful for identifying the causes of build problems when compiling
application projects.
Android Monitor–The Android Monitor tool window provides access to the Android debugging
system. Within this window tasks such as monitoring log output from a running application, taking
screenshots and videos of the application,stopping a process and performing basic debugging tasks
can be performed. The tool also includes real-time GPU, networking, memory and CPU
usage monitors.
Android Model – The Android Model tool window provides a single location in which to view an
exhaustive list of the different options and settings configured within the project. These can range
from the more obvious settings such as the target Android SDK version to more obscure values such
as build configuration rules.
Terminal– Provides access to a terminal window on the system on which Android Studio is running.
On Windows systems this is the Command Prompt interface, while on Linux and Mac OS X systems
this takes the form of a Terminal prompt.
Run – The run tool window becomes available when an application is currently running and
provides a view of the results of the run together with options to stop or restart a running
process.If an application is failing to install and run on a device or emulator, this window will typically
provide diagnostic information relating to the problem.
Event Log – The event log window displays messages relating to events and activities
performed within Android Studio. The successful build of a project, for example,or the fact that
an application is now running will be reported within this tool window.
GradleConsole –The Gradle console is used to display all output from the Gradle system as
projects are built from within Android Studio. This will include information about the success or
otherwise of the build process together with details of any errors or warnings.
Gradle–The Gradle tool window provides a view onto the Gradle tasks that make up the project
build configuration. The window lists the tasks that are involved in compiling the various elements
of the project into an executable application. Right-click on a top level Gradle task and select the
Open Gradle Configmenu option to load the Gradle build file for the current project into the editor.

3.2.3 Fundamental User Interface Design:


Anroid Studio provides an easy way of designing user interfaces. The file named
―activity_main.xml‖ located under the ―res/layout‖ folder contains all the layout information of the
current activity. If we try to open an .xml file outside of Android Studio, it is opened by a text editor
or a browser. However, when we open an .xml file in Android Studio, it reads the .xml file and shows
the corresponding activity layout with its components. In order to open the activity_main.xml in
Android Studio, double-click on it in the project explorer and the activity layout will be displayed in
the middle pane as shown below:

PREPARED BY MRS. V.R.SONAR 11


Fig. 3.2.5. Layout of the activity
As you can see, the layout of the activity is shown in the middle pane. The name of the app appears
at the top of the activity. The default empty activity contains a default text which is shown inside
the circle in the above figure. At the left top of the middle pane, there exists a tab called ―Palette‖
indicated inside the rectangle in the figure. When we click on this tab, the palette shown in Figure
Fig. 3.2.6 appears from which we can add all possible user interface objects and layout templates to
the activity.

Fig. 3.2.6. The component palette


When the palette tab is clicked, two panes are opened: the Palette shown by the upper rectangle and
the Component Tree pane inside the lower rectangle in Figure Fig. 3.2.6. The Palette contains several
groups like Widgets, Text Fields and Layouts. We can easily drag and drop these components to the
user interface. On the other hand, the Component Tree lists the activity‟s components in a hierarchical
manner..As you can see from Figure Fig. 3.2.6, Android Studio already placed a ―Hello World‖ text
at the top left of the view.
Let‘s position this text, comprised of a TextView widget, to the middle of the view. For this, select
PREPARED BY MRS. V.R.SONAR 12
this TextView and then drag and drop to the middle by the help of the guiding lines as shown below:

Fig. 3.2.7. Drag and drop operation on the TextView


After the drag and drop operation, the TextView will be kept selected. We can now change the
properties of the TextView using the Properties pane which is at the right of the Layout view as shown
inside the rectangle in Figure Fig. 3.2.8. Click the arrow shown inside the circle in this figureto open
the basic editable properties of the TextView.

Fig. 3.2.8 The Properties pane


The editable properties of the TextView component are shown inside the rectangle in Figure.
3.2.4. Building the Project and Running on an Emulator :
to be run Our first Android app on an emulator follow the steps given below:.

i) building the project,

PREPARED BY MRS. V.R.SONAR 13


ii) selecting the emulator
iii) run our app on the emulator.

Fig. 3.2.9. The editable properties of the TextView


In order to build and run the project, please click the ―Run‖ button as indicated by the arrow in
Figure 3.2.9. The emulator and device selection dialog shown in Figure 3.2.10 will appear. When the
emulator starts running, you will see a Nexus 5 screen as shown in Figure 3.2.11.

Fig. 3.2.10 Selecting the target for running our first app

PREPARED BY MRS. V.R.SONAR 14


Fig. 3.2.11. The Nexus 5 emulator
3.2.5. Running on a Real Device
It is also easy to try our app on a real Android device.
1. Things to be done on the device: Before running/debugging apps on the real device, we have to
enable the Developer Mode on the device.
For this, on your real device please navigate to Settings  About Build number or Settings 
About Software information  Build number. Depending on your device and Android version, the
place of the “Build number” may be different however I‟m sure you can find it easily in the
Settings  About section. Once you find the Build number, tap on it seven times and then your
device will show a dialog box saying ―You are now a developer.‖ After you‟ve enabled the
Developer Mode, you‟ll find a new section
called ―Developer options‖ under the Settings of your device. Please tap on it and then check ―USB
debugging‖ to enable debugging via the USB connection. You can now install apps from Android
Studio to your device over the usual USB connection.
2. Things to be done in Android Studio: First of all, please enable ―ADB Integration‖ from Tools
 Android  ADB Integration as shown below:

Fig. 3.2.12 Enabling ADB Integration in Android Studio


Now, we need to make our app ―debuggable‖. For this, open the AndroidManifest.xml file by
double-clicking on it and add the text android:debuggable="true" inside the <application> element
as shown in Fig. 3.2.13.

PREPARED BY MRS. V.R.SONAR 15


Fig. 3.2.13 Adding the ―debuggable‖ property to our app
We are now ready to test our ―Hello World‖ app on the real device.When we hit the ―Run‖ button in
Android Studio, the following device selection window will appear:

Fig. 3.2.14 Selecting the real device


I have connected my Asus Zenfone 6 hence its name is written in the device selection window; it will
obviously be different if the device you connected is different. After the device selection, click on the
―OK‖ button and then the app screen of Fig. 3.2.14 should appear on your actual device. If you see
the ―Hello World!‖ text on the real device, it‟s excellent. You now know how to install your apps
on real Android
devices. Running an app on a real hardware is sometimes essential because some operations like SMS
sending and calling can only be done on real devices.
We have developed out test drive app, ―Hello World‖, and learned
i) Creating an Android Studio project,
ii) Using user interfaces and widgets,
iii) Creating emulators,
iv) Building the app,
v) Running our app on the emulator,
vi) Running our app on a real device.

3.3 Components of Android Application:


Almost all popular applications are interactive. These applications interact with the user, and,
depending on the data supplied by the user, desired actions and/or processing are performed. The user
interface controls thus play a major role in getting feedback from the user. Applicationcomponents
are the ones which when combined together, offers you a brilliant Android application. So, these
components exactly act as the building blocks of an Android application. The information
PREPARED BY MRS. V.R.SONAR 16
regarding all the application components is provided in the manifest file, which is
AndroidManifest.xml. This file will help you in understanding the use of each and every application
component and how do they interact with each other.

Android provides four important components to build any android application.

 Activities
 Services
 Intent and broadcast receivers
 Content Providers

Fig. 3.3.1 components of android application

1. Activities-
Activities are said to be the presentation layer of our applications. An activity is the first
stepping stone is building an Android user application. The UI of our application is build around one
or more extensions of the Activity class.
An activity in android is like your computer welcome screen which presents single user display. In
other words, Activity in android represents single screen with a user interface. We can understand
Activity in terms of web applications For example: We creates numbers of web pages to build
complete web application, similarly on the other hand android application consist of several Activities
to run as a complete application. There is one ―main‖ activity. All other activities are child
activities. There is a stack called back stack. Whenever, there is a new window is started, previous
activity is pushed to the back stack and it is stopped until the new activity is done. As soon as the
back key of your device is pressed, new activity is popped out of stack and destroyed. Now previous
activity resumes.
2. Services-
These are like invisible workers of our app. These components run at backend, updating
your data sources and Activities, triggering Notification and also broadcast Intents. They also perform
some tasks when applications are not active. This component is responsible for handling

PREPARED BY MRS. V.R.SONAR 17


the time taking operations which generally runs in the background of the operating system (in this
case, Android). The simple example of the service component is that when you play music on your
mobile phone, you will be able to use other applications too. A service can take two forms:
a. Started: After a service starts, it can run indefinitely and usually performs single operation.
No result is returned to user. For example, uploading a file. After the task is completed, it
should terminate itself.
b. Bound: In this case, a component is bound to a service so that a particular task can be
completed. This type of service provides a client-server like interface. Requests can be send,
receive requests, and return result to the user. Inter process communication is achieved through
this service.

3.Intents and Broadcast Receivers-


Android Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc. It is generally used with startActivity( ) method to invoke
activity, broadcast receivers etc. It binds individual components to each other. Broadcast Receivers
simply respond to broadcast messages from other applications or from the system itself. These
messages are sometime called events or intents. For example, applications can also initiate broadcasts
to let other applications know that some data has been downloaded to the device and is available for
them to use, so this is broadcast receiver who will intercept this communication and will initiate
appropriate action. another example is, when your device boots up or switched on, the system
generates a broadcast to all apps. There should be a procedure or should be something which can
receive these broadcasts. These receptors are called broadcast receivers. There are two types of
broadcasts:
a. Normal Broadcasts: These are asynchronous in nature. Many receivers can be activated at
the same time which doesn‘t have any defined order. But they are very efficient.
b. Ordered Broadcasts: They are synchronous in nature. Broadcast received by one receiver
passes it to other receivers. Broadcasts are delivered to receiver on one-to-one and sequential
basis. Either receiver will pass result to another receiver or it may completely destroy the
broadcast.

4. Content Providers- It is used to manage and persist the application data also typically interact
with SQL database. They are also responsible for sharing the data beyond the application boundaries.
The Content Providers of a particular application can be configured to allow access from other
applications, and the Content Providers exposed by other applications can also beconfigured. With
content providers we can save data in SQLite database, on the web or any other persistent storage
location, where application can easily access the data. This component is useful inreading and writing
private data. For example: we can read and write important reminders or notesin database(within an
application).
5. Android Widgets and Notifications
 Android App widgets are the small application views. These views can be embedded into
other applications. They can receive updates on periodic basis. A widget is a quick view of
your app‘s functionality and data. This view is accessible from home screen of your device.
Now widgets are of following types:

Fig. 3.3.2 types of widgets

PREPARED BY MRS. V.R.SONAR 18


a. Informational Widget: These Android widgets are going to display only that information
to user which is important and dynamic in nature. Example the information displayed on your
home screen saying time and weather condition is a widget of this type.
b. Collection Widgets: These Android widgets scroll in top-to-down direction. Collection of
information of same type and then enabling user to open any one of them to full detail.
Example is your e-mail app which will display all the mails in your inbox and then allow
you to open any one o them.
c. Control Widgets: Displays the most frequently used functionalities which user might want
to control from home screen. For example in a video app, you can pause, play, stop, go to
previous track, move to next track is an example of control widget.
d. Hybrid Widgets: These Android widgets combine features of all of the above three.
 Notification, as the name says keeps the user aware of events going on. User is kept informed
like any news channel. For e.g, everyone of us know about facebook or whatsapp, now
notification system of app is responsible for informing you about any new friend request, chat
request, or a new message from say, dvs or xyz, etc.
There are a few other application components that you should be aware of. These application
components include fragments, views, layouts, intents, resources, and manifest. All of these
components are used for the creation of above components.
S.No. Application Description
Components
1 Fragments Represents the fragments of a user interface in the Activity component
2 Views Includes the user interface elements like buttons, drop-down lists, etc.
3 Layouts Controls the screen format based on different hierarchies of the views
Takes care of the appearance of the views on the screen
4 Intents Wires the messages of different components together
5 Resources Includes external elements like drawable or editable pictures, strings,
and constants
.
3.3.1 CREATING THE USER INTERFACE :
There are three approaches to creating user interfaces in Android.
1. You can create user interfaces entirely in Java code
2. Entirely in XML
3. Combining both methods (defining the user interface in XML and then referring and modifying it
through Java code).

The third approach, the combined approach, is highly preferred.


The graphical user interface for an Android app is built using a hierarchy of View and ViewGroup
objects.
 A View is an interactive UI component (or widget or control), such as button and text field.
It controls a rectangular area on the screen. It is responsible for drawing itself and handling
events (such as clicking, entering texts). Android provides many ready-to-use Views suchas
TextView, EditText, Button, RadioButton, etc, in package android.widget. You can also
create your custom View by extending android.view.View.
 A ViewGroup is an invisible container used to layout the View components. Android
provides many ready-to-use ViewGroups such as LinearLayout, RelativeLayout,
TableLayout and GridLayout in package android.widget. You can also create your custom
ViewGroup by extending from android.view.ViewGroup.

Views and ViewGroups are organized in a single tree structure called view-tree. You can create a
view-tree either using programming codes or describing it in a XML layout file.
Layout view groups:

PREPARED BY MRS. V.R.SONAR 19


The views for a screen are organized in a hierarchy. At the root of this hierarchy is a ViewGroup that
contains the layout of the entire screen. The view group's child screens can be other views or other
view groups as shown in the following figure.
1. The root view group.
2. The first set of child views and view groups whose parent is the root.

Figure3.3.3 : ViewGroup objects form branches in the layout and contain other View objects.

COMMONLY USED LAYOUTS AND CONTROLS :


The views or the controls that we want to display in an application are arranged in an order or sequence
by placing them in the desired layout. The layouts also known as Containers or ViewGroups. These
are used for organizing the views or controls in the required format. Android provides the following
layouts
• LinearLayout: In this layout, all elements are arranged in a descending column from top to bottom
or left to right. Each element contains properties to specify how much of the screen space it will
consume. Depending on the orientation parameter, elements are either arranged in row or column
format.
• RelativeLayout:In this layout, each child element is laid out in relation to other child elements.
That is, a child element appears in relation to the previous child. Also, the elements are laid out in
relation to the parent.
• AbsoluteLayout: In this layout, each child is given a specific location within the bounds of the
parent layout object. This layout is not suitable for devices with different screen sizes and hence is
deprecated.
PREPARED BY MRS. V.R.SONAR 20
• FrameLayout: This is a layout used to display a single view. Views added to this are always placed
at the top left of the layout. Any other view that is added to the FrameLayout overlaps the previous
view; that is, each view stacks on top of the previous one.
• TableLayout: In this layout, the screen is assumed to be divided in table rows, and each of the
child elements is arranged in a specific row and column.
• GridLayout: n this layout, child views are arranged in a grid format, that is, in the rows and columns
pattern. The views can be placed at the specified row and column location. Also, more than one view
can be placed at the given row and column position.
The following is list of some commonly used controls in Android applications:
• TextView:A read-only text label. It supports multiline display, string formatting, and
automatic word wrapping.
• EditText: An editable text box that also accepts multiline entry and word-wrapping.
• ListView: A ViewGroup that creates and manages a vertical list of views, displaying them
as rows within the list.
• Spinner: A TextView and an associated list of items that allows us to select an item from
the list to display in the text box.
• Button: A standard command button.
• CheckBox: A button allowing a user to select (check) or unselect (uncheck).
• RadioButton: A mutually exclusive button, which, when selected, unselects all other
buttons in the group.

3.4 Layouts:
Layouts are basically containers for other items known as Views , which are displayed on the
screen. Layouts help manage and arrange views as well. Layouts are defined in the form of XML
files that cannot be changed by our code during runtime.
Following table shows the layout managers provided by the Android SDK.
Layout Manager Description

LinearLayout Organizes its children either horizontally r vertically


RelativeLayout Organizes its children relative to one another or to the parent
AbsoluteLayout Each child control is given a specific location within the bounds of the
container

FrameLayout Displays a single view; that is, the next view replaces the previous view and
hence is used to dynamically change the children in the layout
TableLayout Organizes its children in tabular form
GridLayout Organizes its children in grid format

PREPARED BY MRS. V.R.SONAR 21


Fig. 3.3.4 layouts supported by android system
Let‘s get familiar with the layout editor :
The layout editoris used to edit the layout file. You can drag and drop view objects
into a graphical pane, and arrange, resize, and specify properties for them. Youimmediately
see the effect of changes you make.
To use the layout editor, open the XML layout file. The layout editor appears with the
Design tab at the bottom highlighted.
(If the Text tab is highlighted and you see XML code, click the Design tab.) For the Empty
Activity template, the layout is as shown in the figure below.

Fig. 3.3.5 the layout editor window


In the figure above:
1. XML layout file. The XML layout file, typically named activiy_main.xml file.Double-click it
to open the layout editor.
2. Palette of UI elements (views). The Palette pane provides a list of UI elements and layouts.Add
an element or layout to the UI by dragging it into the design pane.
3. Design toolbar.The designpane toolbar provides buttonsto configure your layout appearance in
the design pane and to edit the layout properties.See the figure 3.3.6 for details.
4. Properties pane. The Properties pane provides property controls for the selected view.

PREPARED BY MRS. V.R.SONAR 22


5. Property control. Property controls correspond to XML attributes. Shown in the figure is the
Text property of the selected TextView, set to Hello World!.
6. Design pane. Drag views from the Palette pane to the design pane to position them in the
layout.
7. Component Tree. The Component Tree pane shows the view hierarchy. Click a view or view
Group in this pane to select it.The figure shows the TextView selected.
8. Design and Text tabs. Click Design to see the layout editor, or Text to see XML code.The
layout editor's design toolbar offers a row of buttons that let you configure the appearance of
the layout:

Fig.3.3.6 Design toolbar


In the figure above:
1. Design, Blueprint and Both: Click the Design icon (first icon) to display a color preview of
your layout.Click the Blueprint icon (middle icon) to show only outlines for each view. You can
see both views side by side by clicking the third icon.
2. Screen orientation: Click to rotate the device between landscape and portrait.
3. Device type and size: Select the device type (phone/tablet, Android TV, or Android Wear) and
Screen configuration (size and density).
4. API version: Select the version of Android on which to preview the layout.
5. App theme: Selectwhich UI theme to apply to the preview.
6. Language: Select the language to show for your UI strings. This list displays only th languages
available in the string resources.
7. Layout Variants: Switch to one of the alternative layouts for this file, or create a new one.

3.4.1 Android Linear Layout :


 In android, LinearLayout is a ViewGroup subclass which is used to render all child
View instances one by one either in Horizontal direction or Vertical direction based on the
orientation property.
 Linear layout in Android allow us to arrange components horizontally in a single column or
vertically in a single row. Vertically or horizontally direction depends on attribute android:
orientation.
 Linear layout is simple and easy to use, it creates a scroll bar if the length of the window
exceeds the length of the screen. Vertically linear layout has only one item per row.
 Linear layout has many different attributes which can be used to customize linear layout
according to needs.
 . There are two types of linear layout orientation:
1. Vertical
2. Horizontal

PREPARED BY MRS. V.R.SONAR 23


.
Fig. 3.3.7 Types of layouts
1. Vertical:

In this all the child are arranged vertically in a line one after the other.
2. Horizontal:
In this all the child are arranged horizontally in a line one after the other.
Android LinearLayout Declaration:

In above code snippet, the orientation is defined as vertical, so this aligns all its child layout /
views vertically.
Android LinearLayout Example
Following is the example of creating a LinearLayout with different controls in android application.
Steps:
1. Create a new android application using android studio and give names as LinearLayout.
2. Now open an activity_main.xml file from \res\layout path and write the code like as shown
below:
activity_main.xml

PREPARED BY MRS. V.R.SONAR 24


<?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:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<EditText
android:id="@+id/txtTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"/>
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"/>
<EditText

PREPARED BY MRS. V.R.SONAR 25


android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Message"/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send"/>
</LinearLayout>
3. After creation of layout, load the XML layout resource from activity onCreate() callback
method,for that open main activity file
MainActivity.java from \java\com.vrs.linearlayout path and write the code like as shown
below.
MainActivity.java
package com.vrs.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Note: In above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file
name activity_main.
Generally, during the launch of our activity, onCreate() callback method will be called by android
framework to get the required layout for an activity.
Output of Android LinearLayout Example
When we run above example using android virtual device (AVD) we will get a result like as shown
below.

PREPARED BY MRS. V.R.SONAR 26


Attributes of linear layout
Following are some attributes of linear layout of Android.
Attribute Description
This is the ID which uniquely identifies the view.
android:id
This is the width of the layout.
android:layout_width
This is the height of the layout
android:layout_height
This is the extra space on the top side of the layout.
android:layout_marginTop
This is the extra space on the bottom side of the layout.
android:layout_marginBottom
This is the extra space on the left side of the layout.
android:layout_marginLeft
This is the extra space on the right side of the layout.
android:layout_marginRight
This specifies how child Views are positioned.
android:layout_gravity
This specifies how much of the extra space in the layout
android:layout_weight
should be allocated to the View.
This specifies the x-coordinate of the layout.
android:layout_x
This specifies the y-coordinate of the layout.
android:layout_y
This is the left padding filled for the layout.
android:paddingLeft
This is the right padding filled for the layout.
android:paddingRight
This is the top padding filled for the layout.
oandroid:paddingTop
This is the bottom padding filled for the layout.
android:paddingBottom

PREPARED BY MRS. V.R.SONAR 27


1. orientation:
 The orientation attribute used to set the childs/views horizontally or vertically.
 In Linear layout default orientation is vertical.
 The valid values for this attribute are horizontal and vertical .
 If the value of the android:orientation attribute is set to vertical , the children in the linear
layout are arranged in a column layout, one below the other.
 If the value of the android:orientation attribute is set to horizontal , the controls in the linear
layout are arranged in a row format, side by side.
 The orientation can be modified at runtime through the setOrientation() method. That is, by
supplying the values HORIZONTAL or VERTICAL to the setOrientation() method, we can
arrange the children of the LinearLayout in row or column format, respectively as shown
below:
For vertical -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:orientation="vertical"> <!-- Vertical Orientation set -->


<!-- Put Child Views like Button here -->
</LinearLayout>

For horizontal -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> <!-- Horizontal Orientation set -->
<!-- Child Views are here -->
</LinearLayout>

Example 1: Orientation vertical:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".LinearLayout" >

<Button
android:text="BUTTON"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 1"
android:paddingTop="10px"/>

<TextView

PREPARED BY MRS. V.R.SONAR 28


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 2"
android:paddingTop="10px"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 3"
android:paddingTop="10px"/>

</LinearLayout>

Output:

Example 2: Orientation Horizontal:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".LinearLayout" >

<Button
android:text="BUTTON"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 1"
PREPARED BY MRS. V.R.SONAR 29
android:paddingTop="10px"
android:paddingLeft="10px"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 2"
android:paddingTop="10px"
android:paddingLeft="10px"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 3"
android:paddingTop="10px"
android:paddingLeft="10px"/>
</LinearLayout>
Output:

2. gravity:
 The gravity attribute is an optional attribute for aligning the content within a control.
For example, to align the text of a control to the right, we set the value of its
android:gravity attribute to right .
 The valid options for android:gravity include left , center , right , top , bottom ,
center_horizontal , center_vertical , fill_horizontal , and fill_vertical .
 The task performed by few of the above options is as follows:
 center_vertical :
Places the object in the vertical center of its container, without
changing its size
 fill_vertical :
Grows the vertical size of the object, if needed, so it completely fills its container
 center_horizontal :
PREPARED BY MRS. V.R.SONAR 30
Places the object in the horizontal center of its container,without changing its size
 fill_horizontal :
Grows the horizontal size of the object, if needed, so it completely fills its container
 center:
Places the object in the center of its container in both the vertical and horizontal
axis, without changing its size
Example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="horizontal">

<!--Button Child View Here--->

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click2"
android:id="@+id/click2"
android:background="#0e7d0d" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click1"
android:id="@+id/click"
android:background="#761212" />
</LinearLayout>
Output:

3. layout_weight:
 The layout weight attribute specify each child control‘s relative importance within the parent
linear layout.
 The weight attribute affects the size of the control. That is, we use weight to assign the
PREPARED BY MRS. V.R.SONAR 31
capability to expand or shrink and consume extra space relative to the other controls in
the container.
 The values of the weight attribute range from 0.0 to 1.0 , where 1.0 is the highest value.
Let‘s suppose a container has two controls and one of them is assigned the weight of 1 . In
that case, the control assigned the weight of 1 consumes all the empty space in the container,
whereas the other control remains at its current size. If we assign a weight of 0.0 to both the
controls, nothing happens and the controls maintain their original size.
 If both the attributes are assigned the same value above 0.0 , both the controls consume the
extra space equally. Hence, weight lets us apply a size expansion ratio to the controls.
Example:

<?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="horizontal">
<!--Add Child View Here--->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Weight 2"
android:background="#5b39c6"
android:layout_margin="5dp"
android:id="@+id/button"
android:layout_weight="2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00ff00"
android:layout_margin="5dp"
android:layout_weight="1"
android:text="Weight 1" />
</LinearLayout>
Output:

4. WeightSum:
 weightSum is the sum up of all the child attributes weight.
 This attribute is required if we define weight property of the childs.
Example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="3"
android:orientation="horizontal">

PREPARED BY MRS. V.R.SONAR 32


<!--Add Child View Here--->
</LinearLayout>

5. layout_width and layout_height:


 The default height and width of a control are decided on the basis of the text or content
that is displayed through it.
 To specify a certain height and width to the control, the android:layout_width and
android:layout_height attributes is used.
 The values for the height and width attributes can be specified in the following three ways:
 By supplying specific dimension values for the control in terms of px (pixels), dip/
dp (device independent pixels), sp (scaled pixels), pts (points), in (inches), and mm
(millimeters). For example, the android:layout_width="20px" attribute sets the
width of the control to 20 pixels.
 By providing the value as wrap_content . When assigned to the control‘s height or
width, this attribute resizes the control to expand to fit its contents. For example,
when this value is applied to the width of the TextView , it expands so that its
complete text is visible.
 By providing the value as match_parent . When assigned to the control‘s height or
width, this attribute forces the size of the control to expand to fill up all the available
space of the enclosing container.
 For layout elements, the value wrap_content resizes the layout to fit the controls added as its
children. The value match_parent makes the layout expand to take up all the space in the
parent layout.
 It will control the width and height of the linear layout.
 If you want to give full width and height then set layout_width and layout_height
as match_parent.
 Set layout_width and layout_height as wrap_content if you want to have width of
linearlayout as per requirements of children widgets.
 You can set layout_width in units also. For example 10dp,20dp etc.
 The higher the dp number the more width is there.

6. Applying the padding Attribute:


 The padding attribute is used to increase the whitespace between the boundaries of
the control and its actual content.
 Through the android:padding attribute, we can set the same amount of padding or spacing on
all four sides of the control.
 Similarly, by using the android:paddingLeft , android:paddingRight , android:paddingTop ,
and android:paddingBottom attributes, we can specify the individual spacing on the left, right,
top, and bottom of the control, respectively.
 For example-1) to add padding of 16dp to all edges of the layout:

PREPARED BY MRS. V.R.SONAR 33


2) different amounts of padding to different edges

 To set the padding at runtime, we can call the setPadding() method.

Example 1: First we will design Android Linear Layout without using weight property
In this example we have used one TextView and 4 Button. The orientation is set to vertical.
Below is the code of activity_main.xml
<!-- Vertical Orientation is set -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Text Displayed At Top -->

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Linear Layout (Without Weight)"
android:id="@+id/textView"

PREPARED BY MRS. V.R.SONAR 34


android:layout_gravity="center_horizontal" />

<!-- Button Used -->

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:background="#e6cf00" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3"
android:background="#0472f9" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 4"
android:background="#e100d5" />
</LinearLayout>
Output :

Example 2: In this example of linear layout we have used weight property.


Below is the code of activity_main.xml with explanation included
<!-- Vertical Orientation is set with weightSum-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="5"
android:orientation="vertical">

<!-- Text Displayed At Top -->

PREPARED BY MRS. V.R.SONAR 35


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Linear Layout (With Weight)"
android:id="@+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="0"/>

<!-- Button Used -->

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300"
android:layout_weight="1"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:background="#e6cf00"
android:layout_weight="1"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3"
android:background="#0472f9"
android:layout_weight="1"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 4"
android:background="#e100d5"
android:layout_weight="1"/>
</LinearLayout>
Output:

PREPARED BY MRS. V.R.SONAR 36


Example 3: Mixed Example With Horizontal And Vertical Orientation Properties :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:orientation="vertical"
tools:context=".LinearLayout" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="10px"
android:paddingTop="20px"
android:text="LOGIN" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20px">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10px"
android:paddingTop="20px"
android:text="Username" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:layout_marginLeft="40px"
android:paddingTop="20px" />

</LinearLayout>
PREPARED BY MRS. V.R.SONAR 37
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20px"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:paddingTop="20px"
android:paddingLeft="10px"/>

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="40px"
android:layout_weight="0.50"
android:paddingTop="20px" />

</LinearLayout>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="20px"
android:paddingTop="10px"
android:text="BUTTON" />
</LinearLayout>
Output

PREPARED BY MRS. V.R.SONAR 38


• The formula for converting dp to px (pixels) is as

PREPARED BY MRS. V.R.SONAR 39


follows:
• Actual pixels = dp * (dpi / 160),
where dpi is either 120, 160, 240, or 320.
• Low density (ldpi) — 120 dpi
• Medium density (mdpi) — 160 dpi
• High density (hdpi) — 240 dpi
• Extra High density (xhdpi) — 320 dpi

Resource files
Resource files are a way of separating static values from code so that you don't have to change the code
itself to change the values. You can store all the strings, layouts, dimensions, colors, styles, and menu
text separately in resource files. Resource files are stored in folders located in the res folder, including:
 drawable: For images and icons
 layout: For layout resource files
 menu: For menu items
 mipmap: For pre-calculated, optimized collections of app icons used by the
Launcher
 values: For colors, dimensions, strings, and styles (theme attributes)
The syntax to reference a resource in an XML layout is as follows:
@package_name:resource_type/resource_name

The package_name is the name of the package in which the resource is located. This is not
required when referencing resources from the same package — that is, stored in the res folder of
your project.
resource_type is the R subclass for the resource type. See Resource Types for more
information about each resource type and how to reference them.
resource_name is either the resource filename without the extension, or the android:name
attribute value in the XML element.
For example, the following XML layout statement sets the android:text attribute to a string resource:

android:text="@string/button_label_toast"

The resource_type is string .


The resource_name is button_label_toast.
There is no need for a package_name because the resource is stored in the project (in the
strings.xml file).

Another example: this XML layout statement sets the android:background attribute to a color
resource, and since the resource is defined in the project (in the colors.xml file), the

android:background="@color/colorPrimary"

package_name is not specified:


In the following example, the XML layout statement sets the android:textColor attribute to a color
resource. However, the resource is not defined in the project but supplied by Android, so the
package_name android must also be specified, followed by a colon:

android:textColor="@android:color/white"

PREPARED BY MRS. V.R.SONAR 40


Values resource files

Keeping values such as strings and colors in separate resource files makes it easier to manage them,
especially if you use them more than once in your layouts.
For example, it is essential to keep strings in a separate resource file for translating and localizing
your app, so that you can create a string resource file for each language without changing your
code. Resource files for images, colors, dimensions, and other attributes are handy for developing
an app for different device screen sizes and orientations.

Strings

String resources are located in the strings.xml file in the values folder inside the res folder when
using the Project: Android view. You can edit this file directly by opening it:

<resources>
<string name="app_name">Hello Toast</string>

<string name="count_initial_value">0</string>
</resources>

The name (for example, button_label_count ) is the resource name you use in your XML code, as in the
following attribute:

android:text="@string/button_label_count"

The string value of this name is the word ( Count ) enclosed within the <string></string> tags
(you don't use quotation marks unless the quotation marks should be part of the string value.)

Extracting strings to resources


You should also extract hard-coded strings in an XML layout file to string resources. To extract
a hard-coded string in an XML layout, follow these steps (refer to the figure):

PREPARED BY MRS. V.R.SONAR 41


1. Click on the hard-coded string, and press Alt-Enter in Windows,
2. Select Extract string resource.
3. Edit the Resource name for the string value.
You can then use the resource name in your XML code. Use the expression
"@string/resource_name" (including quotation marks) to refer to the string resource:

android:text="@string/button_label_count"

Colors
Color resources are located in the colors.xml file in the values folder inside the res folder when
using the Project: Android view. You can edit this file directly:

<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="myBackgroundColor">#FFF043</color>
</resources>

The name (for example, colorPrimary ) is the resource name you use in your XML code:

android:textColor="@color/colorPrimary"

The color value of this name is the hexadecimal color value ( #3F51B5 ) enclosed within the
<color></color> tags. The hexadecimal value specifies red, green, and blue (RGB) values. The value
always begins with a pound ( # ) character, followed by the Alpha-Red-Green-Blue information. For
example, the hexadecimal value for black is #000000, while the hexadecimal value for a variant of
sky blue is #559fe3. Base color values are listed in the Color class documentation.
The colorPrimary color is one of the predefined base colors and is used for the app bar. In a production
app, you could, for example, customize this to fit your brand. Using the base colors for other UI
elements creates a uniform UI.
Tip: For the material design specification for Android colors, see Style and Using the Material Theme.
For common color hexadecimal values, see Color Hex Color Codes. For Android color
PREPARED BY MRS. V.R.SONAR 42
constants, see the Android standard R.color resources.
You can see a small block of the color choice in the left margin next to the color resource
declaration in colors.xml, and also in the left margin next to the attribute that uses the resource
name in the layout XML file.

Tip: To see the color in a popup, turn on the Autopopup documentation feature. Choose Android
Studio > Preferences > Editor > General > Code Completion, and check the "Autopopup
documentation in (ms)" option. You can then hover your cursor over a color resource name to see the
color.

Dimensions
Dimensions should be separated from the code to make them easier to manage, especially if you
need to adjust your layout for different device resolutions. It also makes it easy to have consistent
sizing for views, and to change the size of multiple views by changing one dimension resource.
Dimension resources are located in a dimens.xml file in the values folder inside the res folder when
using the Project: Android view. The dimens.xml shown in the view can be a folder holding more
than one dimens.xml file for different device resolutions. For example, the app created from the
Empty Activity template provides a second dimens.xml file for 820dp.
You can edit this file directly by opening it:

<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="my_view_width">300dp</dimen>
<dimen name="count_text_size">200sp</dimen>
<dimen name="counter_height">300dp</dimen>
</resources>

The name (for example, activity_horizontal_margin ) is the resource name you use in the XML
code:

android:paddingLeft="@dimen/activity_horizontal_margin"
The value of this name is the measurement ( 16dp ) enclosed within the <dimen></dimen> tags.
You can extract dimensions in the same way as strings::
1. Click on the hard-coded dimension, and press Alt-Enter in Windows, or press Option-Return
on Mac OS X.
2. Select Extract dimension resource.
3. Edit the Resource name for the dimension value.

Device-independent pixels ( dp ) are independent of screen resolution. For example, 10px (10
fixed pixels) will look a lot smaller on a higher resolution screen, but Android will scale 1 0dp (10
device-independent pixels) to look right on different resolution screens. Text sizes can also be set
to look right on different resolution screens using scaled-pixel ( sp ) sizes.
Tip: For more information about dp and sp units, see Supporting Different Densities.

Styles
PREPARED BY MRS. V.R.SONAR 43
A style is a resource that specifies common attributes such as height, padding, font color, font
size, background color. Styles are meant for attributes that modify the look of the view.
Styles are defined in the styles.xml file in the values folder inside the res folder when using the
Project: Android view. You can edit this file directly. Styles are covered in a later chapter,
along with the Material Design Specification.

Other resource files


Android Studio defines other resources that are covered in other chapters:
Images and icons. The drawable folder provides icon and image resources. If your app does
not have a drawable folder, you can manually create it inside the res folder. For more
information about drawable resources, see Drawable Resources in the App Resources section
of the Android Developer Guide.
Optimized icons. The mipmap folder typically contains pre-calculated, optimized collections
of app icons used by the Launcher. Expand the folder to see that versions of icons are stored as
resources for different screen densities.

Menus. You can use an XML resource file to define menu items and store them in your
project in the menu folder.

Responding to view clicks


A click event occurs when the user taps or clicks a clickable view, such as a Button, ImageButton,
ImageView (tapping or clicking the image), or FloatingActionButton.
The model-view-presenter pattern is useful for understanding how to respond to view clicks.
When an event occurs with a view, the presenter code performs an action that affects the model
code. In order to make this pattern work, you have to:
Write a Java method that performs the specific action, which is determined by the logic of
the model code — that is, the action depends on what you want the app to do when this
event occurs. This is typically referred to as an event handler.
Associate this event handler method to the view, so that the method executes when the event
occurs.

The onClick attribute


Android Studio provides a shortcut for setting up a clickable view, and for associating an event handler
with the view: use the android:onClick attribute with the clickable view's element in the XML layout.
For example, the following XML expression in the layout file for a Button sets showToast() as the event
handler:

android:onClick="showToast"

When the b utton is tapped, its android:onClick attribute calls the showToast() method.
Write the event handler, such as showToast() referenced in the XML code above, to call other
methods that implement the app's model logic:

public void showToast(View view) {


// Do something in response to the button click.

In order to work with the android:onClick attribute, the showToast() method must be public , return void , and
require a view parameter in order to know which view called the method.
Android Studio provides a shortcut for creating an event handler stub (a placeholder for the method that
you can fill in later) in the Java code for the activity associated with the XML layout. Follow these steps:
1. Inside the XML layout file (such as activity_main.xml), click the method name in the
android:onClick attribute statement.
2. Press Alt-Enter in Windows or Option-Return in Mac OS X, and select Create onClick event handler.

PREPARED BY MRS. V.R.SONAR 44


3. Choose the activity associated with the layout file (such as MainActivity) and click OK. This creates a
placeholder method stub in MainActivity.java.

Updating views
To update a view's contents, such as replacing the text in a TextView, your code must first
instantiate an object from the view. Your code can then update the object, thereby updating the
view.
To refer to the view in your code, use the findViewById() method of the View class, which looks
for a view based on the resource id . For example, the following statement sets mShowCount to be

mShowCount = (TextView) findViewById(R.id.show_count);


the TextView with the resource id show_count :
From this point on, your code can use mShowCount to represent the TextView, so that when
you update mShowCount , the view is updated.
For example, when the following button with the android:onClick attribute is tapped, onClick call s
the countUp() method:
android:onClick="countUp"
You can implement countUp() to increment the count, convert the count to a string, and set the

public void countUp(View


view) { mCount++;
if (mShowCount != null)
mShowCount.setText(Integer.toStrin
g(mCount));

string as the text for the mShowCount object:

Since you had already associated mShowCount with the TextView for displaying the count, the
mShowCount.setText() method updates the text view on the screen

3.4.2 Android Absolute Layout


Android Absolute Layout is a layout type that allows to position the views in the screen using the
X, Y coordinates.
 Absolute Layout enables you to specify the exact location of its children.
 In order to align the views in the screen using absolute layout is very difficult because we have
to manually specify the locations of the screen accurately. That is why Absolute layouts are
less flexible and harder to maintain than other types of layouts in android.
 Each child in an AbsoluteLayout is given a specific location within the bounds of the
container.
 Such fixed locations make AbsoluteLayout incompatible with devices of different screen
size and resolution.
 The controls in AbsoluteLayout are laid out by specifying their exact X and Y positions. The
coordinate 0,0 is the origin and is located at the top-left corner of the screen.

PREPARED BY MRS. V.R.SONAR 45


Android AbsoluteLayout Attributes:
Following are the important attributes of android AbsoluteLayout.
android:id : This is the ID which uniquely identifies the layout.
android:layout_x : This specifies the x-coordinate of the view.
android:layout_y : This specifies the y-coordinate of the view.

Absolute Layout xml snippet


<AbsoluteLayout
android:layout_width=‖50dp‖
android:layout_height=‖wrap_content
android:layout_x=‖25px‖
android:layout_y=‖29px‖>
</AbsoluteLayout>

Android AbsoluteLayout Syntax Code:

<AbsoluteLayout android:id="@+id/absoluteLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</AbsoluteLayout>

Example1:

activity_main.xml
<AbsoluteLayout android:id="@+id/absoluteLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/btn1"
android:text="Login"
android:textColor="@color/colorPrimary"
android:layout_x="50px"
android:layout_y="361px" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/btn2"
android:textColor="@color/colorPrimary"
PREPARED BY MRS. V.R.SONAR 46
android:text="Register"
android:layout_x="350px"
android:layout_y="361px" />

</AbsoluteLayout>
The graphical representation of the above code is as follows.

Example 2:Layout File activity_absolute_layout_app.xml on Arranging Controls in the


AbsoluteLayout Container

<AbsoluteLayout 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="wrap_content"
android:layout_height="wrap_content"
android:text="Student Registration Form"
android:textSize="20sp"
android.textStyle="bold"
android:layout_x="90dip"
android:layout_y="2dip"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student ID:"
android:layout_x="5dip"
android:layout_y="40dip" />
<EditText
android:id="@+id/student_is"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="100dip"
android:layout_x="110dip"
android:layout_y="30dip" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Name:"
android:layout_x="5dip"
android:layout_y="90dip"/>
<EditText
android:id="@+id/student_name"
android:layout_width="200dip"
android:layout_height="wrap_content"
PREPARED BY MRS. V.R.SONAR 47
android:minWidth="200dip"
android:layout_x="110dip"
android:layout_y="80dip"
android:scrollHorizontally="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Marks:"
android:layout_x="5dip"
android:layout_y="140dip" />
<EditText
android:id="@+id/marks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="100dip"
android:layout_x="110dip"
android:layout_y="130dip" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Add New Student"
android:layout_x="80dip"
android:layout_y="190dip" />
</AbsoluteLayout>

The controls in activity_absolute_layout_app.xml are as follows:


 The Student Registration FormTextView is set to appear 90dip from the left and 2dip from the
top side of the container. The size of the text is set to 20sp , and its style is set to bold .
 The Student ID TextView is set to appear 5dip from the left and 40dip from the top side of the
container.
 The student_id EditText control is set to appear 110dip from the left and 30dip from the top
side of the container. The minimum width of the control is set to 100dp .
 The Student Name TextView control is set to appear 5dip from the left and 90dip from the
top side of the container.
 The student_name EditText control is set to appear 110dip from the left and 80dip from the top
side of the container. The minimum width of the control is set to 200dip , and its text is set to
scroll horizontally when the user types beyond its width.
 The Marks TextView is set to appear 5dip from the left and 140dip from the top side of the
container.
 The marks EditText control is set to appear 110dip from the left and 130dip from the top side
of the container. The minimum width of the control is set to 100dip .
 The click_btn Button , Add New Student , is set to appear 80dip from the left and 190dip from
the top side of the container.
If we don‘t specify the x, y coordinates of a control in AbsoluteLayout, it is placed in the origin point,
that is, at location 0,0. If the value of the x and y coordinates is too large, the control does not appear
on the screen. The values of the x and y coordinates are specified in any units, such as sp , in
,mm,and pt. After specifying the locations of controls in the layout file
activity_absolute_layout_app.xml , we can run the application. There is no need to make any changes
in the file AbsoluteLayoutAppActivity.java .
output

PREPARED BY MRS. V.R.SONAR 48


3.4.3 Android Frame Layout

Fig.3.3.8 frame layout supports one view inside it


 Frame layout is the simple layout representation used to organise the control within the user
interface of android application. When we want to display a single item on the display and
block out the other items then frame layout tool is used. Sometimes it is difficult to organize
child views in a way that is scalable to different screen sizes without the children over lapping
each other, in that case the frame layout is used a it can hold a single child view and can block
the other view.
 We can also add multiple children using frame layout and also control their position within
this by simply assigning the gravity tags to each child. In this child view are drawn in the stack
with the feature of stack the recently added is on the top and also last one added is removed
from the top. The size of the frame layout depends on the size of its largest child whether it is
visible or not.
 Using different tags in frame layout you can also determine whether to measure all the children
or just those that are in the visible or in the invisible state when measuring. These can be
simply defined within the XML layout resources and in Java‘ s for programmatically
application. Understanding layout and when to use these layouts is important for good android
application design. When this layout is used correctly, it becomes the fundamental layout in
which many interesting android application user interfaces can be designed.
 When the child content is too large to draw within the bounds of the layout, it
uses the view scroll view to organise the control within the interface.
 When we need a frame around underlying views for our interface, then frame layout
provides the foreground draw able facility in addition to the normal background,this
task is done with the help od XML‘ s attributes.
PREPARED BY MRS. V.R.SONAR 49
 If multiple child view occurs within the frame layout then they are drawn in such a
order such that the last one child view on the top , which is done using the frame
layout.
 Frame layout are the normal layout of choice especially when you want to use the
overlapped view of the design.
 Frame Layout is one of the simplest layout to organize view controls. They are designed to
block an area on the screen.
 Frame Layout should be used to hold child view, because it can be difficult to display single
views at a specific area on the screen without overlapping each other.
 Multiple children can be addes to a FrameLayout and control their position by assigning
gravity to each child, using the android:layout_gravity attribute.
 FrameLayout is used to display a single View .
 The View added to a FrameLayout is placed at the top-left edge of the layout. Any other View
added to the FrameLayout overlaps the previous View ; that is, each View stacks on top of the
previous one.

 Define frame layout using the <FrameLayout> element like this:

Attributes of frame layout:


Lets see different properties of Frame Layout which will be used while designing Android App UI:
1. android:id
 This attribute will give the unique identity to the framelayout.
 When you want to access the framelayout from the JAVA class, this id will give you the
reference via findViewById() method.
 Value of this attribute should be unique across the whole android app to reduce the
complexity.
Example to use id:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frame"
android:layout_width="200dp"
android:layout_height="300dp"
android:foreground="@color/colorAccent"
PREPARED BY MRS. V.R.SONAR 50
tools:context=".MainActivity">
2. android:foreground
 Foreground defines the drawable to draw over the content and this may be a color value.
 Possible color values can be in the form of ―#rgb‖, ―#argb‖, ―#rrggbb‖, or ―#aarrggbb‖. This
all are different color code model used.
Example: to set the blue color for foreground of frameLayout so the ImageView and other child
views of this layout will not be shown.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:foregroundGravity="fill"
android:foreground="#4363d8"><!--foreground color for a FrameLayout-->

<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>

<!-- Imageview will not be shown because of foreground color which is drawn over it-->

<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"
/>
<!--Textview will not be shown because of foreground color is drawn over it-->

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="vrs"/>

</LinearLayout>
</FrameLayout>
Output:

PREPARED BY MRS. V.R.SONAR 51


3. android:foregroundGravity
 This defines the gravity to apply to the foreground drawable.
 Default value of gravity is fill.
 We can set values in the form of ―top‖, ‖center_vertical‖ , ‖fill_vertical‖,
‖center_horizontal‖, ‖fill_horizontal‖, ‖center‖, ‖fill‖, ‖clip_vertical‖, ‖clip_horizontal‖,
‖bottom‖, ‖left‖ or ‖right‖ .
 It is used to set the gravity of foreground. We can also set multiple values by using ―|‖. Ex:
fill_horizontal|top .Both the fill_horizontal and top gravity are set to framelayout.
4. android:visibility
 We can apply this attribute to any child of the framelayout.
 Possible values for visibility are visible, invisible and gone.
 Visible means that the view is present and we can also see it.
 Invisible means that the view is present and we can not see it.
 Gone means that view is not present and so we can not see it.
Example :
android:visibility="visible"
write the below code in activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frame"
android:layout_width="200dp"
android:layout_height="300dp"
tools:context=".MainActivity">

<TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:visibility="invisible"
android:textSize="20sp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:background="@color/colorPrimary"
android:textColor="#fff"
android:text="I am TextView" />

</FrameLayout>
Output :

You can see that Textview is present (blue border rectangle) but we can not see it.

PREPARED BY MRS. V.R.SONAR 52


5. android:measureAllChildren:
 This determines whether to measure all children including gone state visibility or just those
which are in the visible or invisible state of measuring visibility.
 The default value of measureallchildren is false. We can set values in the form
of Boolean i.e. ―true‖ OR ―false‖.
 This may also be a reference to a resource (in the form ―@[package:]type:name―) or theme
attribute (in the form ―?[package:][type:]name―) containing a value of this type.
 If measureallchildren is set true then it will show actual width and height of frame layout
even if the views visibility is in gone state.
Example:
To set the ImageView visibility to gone and measureAllChildren to true.

activity_main.xml
Note: Make sure you have image in Drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:measureAllChildren="true"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:src="@drawable/ic_launcher"/>

</FrameLayout>

code of MainActivity.java . Here we have used Toast to display height and width on screen.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
FrameLayout frame=(FrameLayout)findViewById(R.id.frame);
frame.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int width = frame.getMeasuredWidth();
int height = frame.getMeasuredHeight();
Toast.makeText(getApplicationContext(),"width="+width+" height="+height,Toast.
LENGTH_SHORT).show();

Output:

PREPARED BY MRS. V.R.SONAR 53


Explanation of Example: It measures all the children in the layout. For ex: If we setVisiblity of an
view be gone and set measuresAllChildren property to be true, then also it will also count to that view
which is not visible, but if we set the measuresAllChildren property to be false, then it will not count
to that view which is gone.
Example 1: Frame Layout using layout gravity. Here we will put textview at different position in
Frame Layout. Below is the code and final output:
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<TextView android:text="LeftTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightTop"
android:layout_gravity="top|right" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CentreTop"
android:layout_gravity="top|center_horizontal" />
<TextView android:text="Left"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Right"
android:layout_gravity="right|center_vertical" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Centre"
android:layout_gravity="center" />
<TextView android:text="LeftBottom"
android:layout_gravity="left|bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

PREPARED BY MRS. V.R.SONAR 54


<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightBottom"
android:layout_gravity="right|bottom" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CenterBottom"
android:layout_gravity="center|bottom" />
</FrameLayout>
Step 3: Let the MainActivity.java has default Android code or add the below code:
package vrs.com.A12;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Output:

Example:
activity_main.xml

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


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imgvw1"
android:layout_width="wrap_content"

PREPARED BY MRS. V.R.SONAR 55


android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/garden" />
<TextView
android:id="@+id/txtvw1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="#4C374A"
android:padding="10dp"
android:text="My Garden"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TextView
android:id="@+id/txtvw2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</FrameLayout>
Here we used ImageView to show the image (garden) from drawable folder in framelayout. So add
your image to drawable folder and replace @drawable/garden path with your image path.
open main activity file MainActivity.java from \java\com.vrs.framelayout path and write the
code like as shown below.
MainActivity.java
package com.vrs.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Output:

PREPARED BY MRS. V.R.SONAR 56


Methods of FrameLayout :
To control the framelayout from JAVA class, android gives us the following in-built methods to
use.
1. generateLayoutParams(AttributeSet attrs) :
It Returns a new set of layout parameters based on the supplied attributes set.
2. getAccessibilityClassName() :
Return the class name of this object to be used for accessibility purposes.
3. getMeasureAllChildren() :
 Determines whether all children, or just those in the VISIBLE or INVISIBLE state,
are considered when measuring.
 It will return boolean value. (True or False)
 If it returns false then compiler will consider only VISIBLE or INVISIBLE state of
children of framelayout.
 For true, it will consider VISIBLE, INVISIBLE and GONE state of children of
framelayout.
4. setForegroundGravity(int foregroundGravity)
Describes how the foreground is positioned.
5. setMeasureAllChildren(boolean measureAll)
Sets whether to consider all children, or just those in the VISIBLE or INVISIBLE state,
when measuring.
6. shouldDelayChildPressedState()
Return true if the pressed state should be delayed for children or descendants of this
ViewGroup.
7. generateDefaultLayoutParams()
Returns a set of layout parameters with a width of ViewGroup.LayoutParams.MATCH
_PARENT,and aheight ViewGroup.LayoutParams.MATCH_PARENT.
8. generateLayoutParams(ViewGroup.LayoutParams lp)
Returns a safe set of layout parameters based on the supplied layout params.
9. onLayout(boolean changed, int left, int top, int right, int bottom)
PREPARED BY MRS. V.R.SONAR 57
Called from layout when this view should assign a size and position to each of its children.
10. onMeasure(int widthMeasureSpec, int heightMeasureSpec)
Measure the view and its content to determine the measured width and the measured height.
This method is invoked by measure(int, int) and should be overridden by sub classes to
provide accurate and efficient measurement of their contents.

3.4.4 Android Table Layout

Fig. 3.3.9 Table layout


 The TableLayout is used for arranging the enclosed controls into rows and columns.
 Each new row in the TableLayout is defined through a TableRow object.
 A row can have zero or more controls, where each control is called a cell .
 The number of columns in a TableLayout is determined by the maximum number of cells in
any row.
 The width of a column is equal to the widest cell in that column. All elements are aligned in
a column; that is, the width of all the controls increases if the width of any control in the
column is increased.
 Table Layout containers do not display a border line for their columns, rows or cells. A Table
will have as many columns as the row with the most cells.
 TableLayout is a ViewGroup subclass which is used to display the child View elements in
rows and columns.
 TableLayout will position its children elements into rows and columns and it won‘t display
any border lines for rows, columns or cells.
 The TableLayout in android will work same as HTML table and table will have as many
columns as the row with the most cells. The TableLayout can be explained as <table> and
TableRow is like <tr> element.

PREPARED BY MRS. V.R.SONAR 58


Fig.3.3.10 Row and Column in Table Layout Android

Important Points About Table Layout In Android:


 For building a row in a table we will use the <TableRow> element. Table row objects are
the child views of a table layout.
 Each row of the table has zero or more cells and each cell can hold only one view object
like ImageView, TextView or any other view.
 Total width of a table is defined by its parent container
 Column can be both stretchable and shrinkable. If shrinkable then the width of column can
be shrunk to fit the table into its parent object and if stretchable then it can expand in width
to fit any extra space available.
 We cannot specify the width of the children‘s of the Table layout. Here, width always match
parent width. However, the height attribute can be defined by a child; default value of height
attribute is wrap content.
Basic Table Layout code in XML:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:collapseColumns="0"> <!-- collapse the first column of the table row-->

<!-- first row of the table layout-->


<TableRow
android:id="@+id/row1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- Add elements/columns in the first row-->

</TableRow>
</TableLayout>

Attributes of table layout:


Attributes Where it is used Why it is used

android:stretchColumns TableLayout When a column width is less and you need to


expand(or stretch) it, you use this attribute.

android:shrinkColumns TableLayout When you do not need the extra space in a


column, you can use this attribute to shrink and
remove the space.

android:collapseColumns TableLayout It hides the column of the given index in the


TableLayout.

android:layout_span Any View inside If a view takes only one column width but when
the TableRow you want your view to take more than one
column space, then you can use this attribute.

android:layout_column Any view inside When you want your view present in the first
the TableRow TableRow to appear below the other TableRow's
view, you can use this attribute.

PREPARED BY MRS. V.R.SONAR 59


1. id: id attribute is used to uniquely identify a Table Layout.
<TableLayout
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent/>

2. stretchColumns:
 The default width of a column is set equal to the width of the widest column, but we can
stretch the column(s) to take up available free space using the android:stretchColumns
attribute in the TableLayout.
 The value assigned to this attribute can be a single column number or a comma-delimited
list of column numbers. The specified columns are stretched to take up any available space on
the row.
 Stretch column attribute is used in Table Layout to change the default width of a column which
is set equal to the width of the widest column but we can also stretch the columns to take up
available free space by using this attribute.
 The value that assigned to this attribute can be a single column number or a comma delimited
list of column numbers (1, 2, 3…n).
 If the value is 1 then the second column is stretched to take up any available space in the row,
because of the column numbers are started from 0.
 If the value is 0,1 then both the first and second columns of table are stretched to take up the
available space in the row.
 If the value is ‗*‘ then all the columns are stretched to take up the available space.
Examples:
 android:stretchColumns="1" :
The second column (because the column numbers are zero-based) is stretched to
take up any available space in the row.
 android:stretchColumns="0,1" :
Both the first and second columns are stretched to take up the available space in the row.
 android:stretchColumns="*" :
All columns are stretched to take up the available space.
<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1"> <!-- stretch the second column of the layout-->

<!-- first row of the table layout-->


<TableRow

android:id="@+id/firstRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- first element of the row-->


<TextView

PREPARED BY MRS. V.R.SONAR 60


android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Text 1"
android:textColor="#000"
android:textSize="12dp" />

<TextView

android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:padding="18dip"
android:text="Text 2"
android:textColor="#000"
android:textSize="14dp" />

</TableRow>
</TableLayout>

Output: 1. when android:stretchColumns="1"

2. when android:stretchColumns="2"

3. when android:stretchColumns="*"

PREPARED BY MRS. V.R.SONAR 61


1. shrinkColumns:
 We can shrink or reduce the width of the column(s) using the android:shrinkColumns
attribute in the TableLayout.
 Shrink column attribute is used to shrink or reduce the width of the column‗s. We can specify
either a single column or a comma delimited list of column numbers for thisattribute. The
content in the specified columns word-wraps to reduce their width.
 If the value is 0 then the first column‘s width shrinks or reduces by word wrapping its content.
 If the value is 0,1 then both first and second columns are shrinks or reduced by word wrapping
its content.
 If the value is ‗*‘ then the content of all columns is word wrapped to shrink their widths.
Examples:
 android:shrinkColumns="0":
The first column‘s width shrinks or reduces by wordwrapping its content.
 android:shrinkColumns="*" :
The content of all columns is word-wrapped to shrink their widths.
Example:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="0"> <!-- shrink the first column of the layout-->

<!-- first row of the table layout-->


<TableRow
android:id="@+id/firstRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- first element of the first row-->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Shrink Column Example"
android:textColor="#000"
android:textSize="18dp" />

</TableRow>
</TableLayout>

PREPARED BY MRS. V.R.SONAR 62


2. collapseColumns:

 We can make the column(s) collapse or become invisible through the


android:collapseColumns attribute in the TableLayout.
 We can specify one or more comma-delimited columns for this attribute. These columns are
part of the table information but are invisible.
 We can also make column(s) visible and invisible through coding by passing the Boolean
values false and true , respectively, to the setColumnCollapsed() method in the TableLayout.
For example:
 android:collapseColumns="0" :
 The first column appears collapsed; that is, it is part of the table but is invisible.
It can be made visible through coding by using the setColumnCollapsed()
method.
 collapse columns attribute is used to collapse or invisible the column‘s of a
table layout. These columns are the part of the table information but are
invisible.
 If the values is 0 then the first column appears collapsed, i.e it is the part of
table but it is invisible.
Example :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:collapseColumns="0"> <!-- collapse the first column of the table row-->

<!-- first row of the table layout-->


<TableRow
android:id="@+id/simpleTableLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- first element of the row that is the part of table but it is invisible-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Columns 1"
android:textColor="#000"
android:textSize="18dp" />

PREPARED BY MRS. V.R.SONAR 63


<!-- second element of the row that is shown in the screenshot-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Columns 2"
android:textColor="#000"
android:textSize="18dp" />
</TableRow>
</TableLayout>

Android TableLayout Example1


activity_main.xml

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


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TableRow android:background="#0079D6" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="UserId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
PREPARED BY MRS. V.R.SONAR 64
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Abhi" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Pune" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rohit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Nasik" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Jaya" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Nasik" />
</TableRow>
</TableLayout>

MainActivity.java

package com.vrs.linearlayout;
import android.support.v7.app.AppCompatActivity;
PREPARED BY MRS. V.R.SONAR 65
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
output

Android TableLayout Example2

<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*" android:stretchColumns="*" android:background="#ffffff">

<!-- Row 1 with single column -->


<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">

<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="18dp" android:text="Row 1" android:layout_span="3"
android:padding="18dip" android:background="#b0b0b0"
android:textColor="#000"/>

</TableRow>
PREPARED BY MRS. V.R.SONAR 66
<!-- Row 2 with 3 columns -->

<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 1"
android:layout_weight="1" android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 2"
android:layout_weight="1" android:background="#d3d3d3"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 3"
android:layout_weight="1" android:background="#cac9c9"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
</TableRow>

<!-- Row 3 with 2 columns -->


<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">
<TextView
android:id="@+id/TextView04" android:text="Row 3 column 1"
android:layout_weight="1 android:background="#b0b0b0"
android:textColor="#000000"
android:padding="18dip" android:gravity="center"/>

<TextView
android:id="@+id/TextView04" android:text="Row 3 column 2"
android:layout_weight="1" android:background="#a09f9f"
android:textColor="#000000"
android:padding="18dip" android:gravity="center"/>
</TableRow>
</TableLayout>
Output

PREPARED BY MRS. V.R.SONAR 67


3.4.5 Android Relative Layout

Fig. 3.3.11 Relative layout


 In RelativeLayout, each child element is laid out in relation to other child elements; that
is, the location of a child element is specified in terms of the desired distance from the
existing children.
 In android, RelativeLayout is a ViewGroup which is used to specify the position of child
View instances relative to each other (Child A to the left of Child B) or relative to the parent
(Aligned to the top of parent).
 In android, RelativeLayout is very useful to design user interface because by using relative
layout we can eliminate the nested view groups and keep our layout hierarchy flat, which
improves performance of application.
 Following is the pictorial representation of relative layout in android applications.

Common Attributes of RelativeLayout


1. Center relative to Parent View. The attributes used to set the location of the control relative to
a container are
 android:layout_alignParentTop — The top of the control is set to align with the top
of the container.
 android:layout_alignParentBottom — The bottom of the control is set to align with
the bottom of the container.
 android:layout_alignParentLeft — The left side of the control is set to align with
the left side of the container.

PREPARED BY MRS. V.R.SONAR 68


 android:layout_alignParentRight — The right side of the control is set to align with
the right side of the container.
 android:layout_centerHorizontal — The control is placed horizontally at the center
of the container.
 android:layout_centerVertical — The control is placed vertically at the center of
the container.
 android:layout_centerInParent — The control is placed horizontally and vertically
at the center of the container

When you want to place your Views in the center relative to the parent, you can use the following 3
attributes:
1. android:layout_centerHorizontal="true"
This places the view horizontally in the center of the parent. As our parent view covers the
whole screen of mobile therefore the view gets placed in the middle of the mobile screen
horizontally.
<!-- centerHorizontal example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 center Horizontal"
android:layout_centerHorizontal="true"
android:textSize="20sp"
android:textColor="#000"
/>

2. android:layout_centerVertical="true"
This places the view vertically in the center of the parent. Since the parent view covers the
PREPARED BY MRS. V.R.SONAR 69
whole screen of mobile hence the view gets placed in the middle of the mobile screen
vertically.
<!-- centerVertical example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 center vertical"
android:layout_centerVertical="true"
android:textSize="20sp"
android:textColor="#000"
/>

3. android:layout_centerInParent="true"
This attribute will place the view in the center of the parent. Since the parent in our example
covers the whole screen of mobile, so the view gets placed in the middle of the mobile screen,
both horizontally and vertically.
<!-- centerInParent example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 center in parent"
android:layout_centerInParent="true"
android:textSize="20sp"
android:textColor="#000"
/>

PREPARED BY MRS. V.R.SONAR 70


2. Align by the parent view
These type of attributes make the view act like a chewing gum as it can be fixed to any side of the
parent view using these attributes.

Again, for the example, we are considering our parent view to be a RelativeLayout with height and
width set as match_parent, therefore it will cover the whole screen of mobile. So the complete
screen is our parent view.
1. android:layout_alignParentTop="true"
If you write this attribute for a View, then that view will stick to the top of its parent. Since
the parent covers the whole screen of mobile therefore, the view will appear sticking to the
top-left of the mobile screen.
<!-- alignParentTop example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 align parent top"

PREPARED BY MRS. V.R.SONAR 71


android:layout_alignParentTop="true"
android:layout_margin="20dp"
android:textSize="20sp"
android:textColor="#000"/>

2. android:layout_alignParentBottom="true"
If you write this attribute for a View, then that view will stick to the bottom of its parent. Since
the our parent covers the whole screen of mobile therefore, the view will appear sticking to
the bottom of the mobile screen.
<!-- textView is alignParentBottom -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text Here is AlignParentBottom with bottom margin of 120dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="120dp" />

3. android:layout_alignParentLeft="true"
If you write this attribute for a View, then that view will stick to the left of its parent. Since
the parent in our example covers the whole screen of mobile therefore, the view will appear
sticking to the left of the mobile screen.
<!-- align parent left in Android -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent Left"

PREPARED BY MRS. V.R.SONAR 72


android:layout_alignBottom="@+id/imageView"
android:layout_alignParentLeft="true"
/>

4. android:layout_alignParentRight="true"
If alignParentRight property is true, then it makes the right edge of this view match the right
edge of the parent. The value of align parent right is either true or false. Example:
android:layout_alignParentRight=‖true‖.
<!-- alignRightParent Example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent Right"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentRight="true"
/>

3. Place new View relative to existing sibling View


In a RelativeLayout you can keep(position) the new views relative to other existing views.
Following attributes can be used for doing so.

Suppose there is one view in the center and its id is given as android:id="@+id/main" Therefore,
the other new views can be placed relative to this view as following:
1. android:layout_toLeftOf="@id/main"
This tells the new view that you have to be on the left side of the view whose id is main.
2. android:layout_toRightOf="@id/main"
This tells the new view that you have to be on the right side of the view whose id is main.
3. android:layout_above="@id/main"

PREPARED BY MRS. V.R.SONAR 73


This tells the new view that you have to be above the view whose id is main.
4. android:layout_below="@id/main"
This tells the new view that you have to be below the view whose id is main.
Note: When you assign an id to the View, you write android:id="@+id/main" i.e you write
a + sign after the @ symbol, indicating you are assigning an id to that view. But when you use
that id for other purpose, like above, you are adding a new view relative to an existing view having
the specfied value of id, hence we do not have to mention the + sign. We simply refer itas
android:layout_below="@id/main" i.e without the + sign.
Align new View relative to existing sibling View
If you want to align the new view relative to any existing view, then you can use the following
attributes.

1. android:layout_alignTop="@id/a"
This aligns the top margin of the new view with the top margin of the view having id as a.
2. android:layout_alignBottom="@id/a"
This aligns the bottom margin of the new view with the bottom margin of the view
having id as a.
3. android:layout_alignLeft="@id/a"
This aligns the left margin of the new view with the left margin of the view having id as a.
4. android:layout_alignRight="@id/a"
This aligns the right margin of the new view with the right margin of the view
having id as a.
5. android:layout_alignBaseLine="@id/a"
This aligns the text1 of the new view with the text2 of the view having id as a.

4. above:
 android:layout_above — The control is placed above the referenced control.
Position the bottom edge of the view above the given anchor view ID and must be a reference of the
another resource in the form of id. Example, android:layout_above=‖@+id/textView‖ .
For example, suppose a view with id textview2 is what we want to place above another view with
id textview.
<!-- textView2 is placed above textView-->

PREPARED BY MRS. V.R.SONAR 74


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Text2"
android:id="@+id/textView2"
android:layout_above="@+id/textView"
android:layout_marginBottom="100dp"
android:layout_centerHorizontal="true"/>

 The attributes to control the position of a control in relation to other controls are
 android:layout_below — The control is placed below the referenced control.
 android:layout_toLeftOf — The control is placed to the left of the referenced control.
 android:layout_toRightOf — The control is placed to the right of the referenced
control.
5. alignBottom:
 android:layout_alignBottom — The bottom of the control is set to align with the
bottom of the referenced control.
alignBottom is used to makes the bottom edge of the view match the bottom edge of the given
anchor view ID and it must be a reference to another resource, in the form of id. Example:
android:layout_ alignBottom =‖@+id/button1″
For example align a view with id textView2 Bottom of another view with id textView..
<!-- textView2 alignBottom of textView -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerHorizontal="true"
android:id="@+id/textView2"
android:layout_alignBottom="@+id/textView"
android:text="Text2 alignBottom of Text1"
android:layout_marginBottom="90dp"
/>

PREPARED BY MRS. V.R.SONAR 75


6. alignLeft:
 android:layout_alignLeft — The left side of the control is set to align with the left
side of the referenced control.
alignLeft is used to make the left edge of the view match the left edge of the given anchor view ID
and must be a reference to another resource, in the form of Example: android:layout_ alignLeft
=‖@+id/button1″.
For example align a view with id textView2 left of another view with id textView.
<!-- textView2 alignLeft of textView -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:text="Text2 alignLeft of Text1"
android:layout_below="@+id/textView"
android:layout_marginTop="20dp"/>

7. alignRight:
 android:layout_alignRight — The right side of the control is set to align with the
right side of the referenced control.
alignRight property is used to make the right edge of this view match the right edge of the given
anchor view ID and must be a reference to another resource, in the form like this example:
android:layout_alignRight=‖@+id/button1″
For example align a view with id textView2 right of another view with id textView.

PREPARED BY MRS. V.R.SONAR 76


<!-- textView2 alignRight of textView-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:layout_alignRight="@+id/textView"
android:text="Text2 alignRight of Text1"
android:layout_below="@+id/textView"
android:layout_marginTop="20dp"/>

8. alignStart:
alignStart property is used to makes the start edge of this view match the start edge of the given
anchor view ID and must be a reference to another resource, in the form of like this example:
android:layout_alignStart=‖@+id/button1″
For example align a view with id textView2 start of another view with id textView.
<!-- Text2 alignStart-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:text="Text2 align start of Text1"
android:layout_alignStart="@+id/textView"
/>

9. alignTop:
 android:layout_alignTop — The top of the control is set to align with the top of the
referenced control.

PREPARED BY MRS. V.R.SONAR 77


alignTop property is used to makes the top edge of this view match the top edge of the given
anchor view ID and must be a reference to another resource, in the form like this example:
android:layout_alignTop=‖@+id/button1″.
For example align a view with id textView Top of another image with id imageView.
<!--text is align top on Image-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_alignTop="@+id/imageView"
android:text="Text Here is AlignTop on Image"
/>

10. alignParentEnd: If alignParentEnd property is true, then it makes the end edge of this view
match the end edge of the parent. The value of align parent End is either true or false. Example:
android:layout_alignParentEnd=‖true‖.
For example textView is simply displayed on Image in the end.
<!-- Text displayed in the end of parent image-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent End"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentEnd="true"
/>

PREPARED BY MRS. V.R.SONAR 78


11. alignParentStart: If alignParentStart is true, then it makes the start edge of this view match the
start edge of the parent. The value of align parent start is either true or false. Example:
android:layout_alignParentStart=‖true‖.
For example textView is simply displayed on parent Image in the right side.
<!-- alignParentStart Example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent Start"
android:layout_alignTop="@+id/imageView"
android:layout_alignParentStart="true"
/>

12. For spacing, Android defines two attributes: android:layout_margin and android:padding .
 The android:layout_margin attribute defines spacing for the container, while
android:padding defines the spacing for the view. Let‘s begin with padding.
 android:padding — Defines the spacing of the content on all four sides of the
control. To define padding for each side individually, use android:paddingLeft
,android:paddingRight , android:paddingTop , and android:paddingBottom .
 android:paddingTop — Defines the spacing between the content and the top of the
control.
 android:paddingBottom — Defines the spacing between the content and the bottom
of the control.
 android:paddingLeft — Defines the spacing between the content and the left side of
the control.
 android:paddingRight — Defines the spacing between the content and the right side
of the control.

13. Here are the attributes that define the spacing between the control and the container:
 android:layout_margin — Defines the spacing of the control in relation to the
controls or the container on all four sides. To define spacing for each side individually,
we use the android:layout_marginLeft , android:layout_marginRight ,
android:layout_marginTop , and android:layout_marginBottom options.

PREPARED BY MRS. V.R.SONAR 79


 android:layout_marginTop — Defines the spacing between the top of the control and
the related control or container.
 android:layout_marginBottom — Defines the spacing between the bottom of the
control and the related control or container.
 android:layout_marginRight — Defines the spacing between the right side of the
control and the related control or container.
 android:layout_marginLeft — Defines the spacing between the left side of the
control and the related control or container.

Example
activity_main.xml
<?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"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button3" />

<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btn2"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
PREPARED BY MRS. V.R.SONAR 80
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn4"
android:layout_centerHorizontal="true"
android:text="Button6" />
<Button
android:id="@+id/btn7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:layout_alignParentRight="true"
android:text="Button7" />
</RelativeLayout>

MainActivity.java
package com.vrs.relativelayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Output

Example:
activity_relative_layout_android_example.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
PREPARED BY MRS. V.R.SONAR 81
tools:context=".RelativeLayoutAndroidExample" >

<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:text="LOGIN"
android:layout_marginTop="14dp"
android:textAppearance="?android:attr/textAppearanceLarge"
/>

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text1"
android:layout_marginTop="20dp"
android:text="Username :"
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_toRightOf="@+id/textView1"
/>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="20dp"

android:text="Password :"
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:inputType="textPassword"
/>

<Button
android:id="@+id/btnSubmit"
PREPARED BY MRS. V.R.SONAR 82
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_below="@+id/editText2"
android:layout_centerInParent="true"
android:text="Submit" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="SIGNUP"
android:layout_centerHorizontal="true"/>

</RelativeLayout>
Output

Difference between Linear And Relative Layout:


RELATIVE LAYOUT:
 Every element of relative layout arranges itself to the other element or a parent element.
 It is helpful while adding views one next to other etc
 In a relative layout you can give each child a Layout Property that specifies exactly where it
should go in relative to the parent or relative to other children.
 Views can be layered on top of each other.
LINEAR LAYOUT:
 In a linear layout, like the name suggests, all the elements are displayed in a linear fashion
either vertically or horizontally.
 Either Horizontally or Vertically this behavior is set in android:orientation which is an
property of the node Linear Layout.
android:orientation=‖horizontal‖ or android:orientation=‖vertical‖
 Linear layouts put every child, one after the other, in a line, either horizontally or vertically.

Text and Scrolling Views


TextView

PREPARED BY MRS. V.R.SONAR 83


One view you may use often is the TextView class, which is a subclass of the View class that
displays text on the screen. You can use TextView for a view of any size, from a single character
or word to a full screen of text. You can add a resource id to the TextView, and control how the
text appears using attributes in the XML layout file.

You can refer to a TextView view in your Java code by using its resource id , and update the text
from your code. If you want to allow users to edit the text, use EditText, a subclass of TextView
that allows text input and editing.

TextView attributes

You can use XML attributes to control:

Where the TextView is positioned in a layout (like any other view)


How the view itself appears, such as with a background color
What the text looks like within the view, such as the initial text and its style, size, and color
For example, to set the width, height, and position within a LinearLayout:

<TextView
...
android:layout_width="match_parent"
android:layout_height="wrap_content"
… />

To set the initial text value of the view, use the android:text attribute:

android:text="Hello World!"

You can extract the text string into a string resource (perhaps called hello_world ) that's easier
to maintain for multiple- language versions of the app, or if you need to change the string in the
future. After extracting the string, use the string resource name with @string/ to specifythe
text:

android:text="@string/hello_world"

The most often used attributes with TextView are the following:

android:text: Set the text to display.


android:textColor: Set the color of the text. You can set the attribute to a color value, a
predefined resource, or a theme. Color resources and themes are described in other chapters.
android:textAppearance: The appearance of the text, including its color, typeface, style, and size.
You set this attribute to a predefined style resource or theme that already defines these values.
android:textSize: Set the text size (if not already set by android:textAppearance ). Use sp (scaled-
pixel) sizes such as 20sp or 14.5sp , or set the attribute to a predefined resource or theme.
android:textStyle: Set the text style (if not already set by android:textAppearance)
normal bold

PREPARED BY MRS. V.R.SONAR 84


Use,
bold | italic .

PREPARED BY MRS. V.R.SONAR 85


Android:typeface: Set the text typeface (if not already set by android:tex pearance ). Use
monospace .
android:lineSpacingExtra: Set extra spacing between lines of text. Use sp (scaled-pixel)
or dp (device-independent pixel) sizes, or set the attribute to a predefined resource or theme.
android:autoLink: Controls whether links such as URLs and email addresses are
automatically found and converted to clickable (touchable) links. Use one of the following:
none : Match no patterns (default).
web : Match web URLs.
email : Match email addresses.
phone : Match phone numbers.
map : Match map addresses.
all : Match all patterns (equivalent to web|email|phone|map).
For example, to set the attribute to match web URLs, use this:

android:autoLink="web"

Using embedded tags in text


In an app that accesses magazine or newspaper articles, the articles that appear would probably
come from an online source or might be saved in advance in a database on the device. You can
also create text as a single long string in the strings.xml resource.
In either case, the text may contain embedded HTML tags or other text formatting codes. To
properly display in a text view, text must be formatted following these rules:
If you have an apostrophe (') in your text, you must escape it by preceding it with a
backslash (\'). If you have a double- quote in your text, you must also escape it (\"). You
must also escape any other non-ASCII characters. See the "Formatting and Styling" section
of String Resources for more details.
The TextView ignores all HTML tags except the following:
Use the HTML and </b> tags around words that should be in bold.
Use the HTML and </i> tags around words that should be in italics. Note, however, that
if you use curled apostrophes within an italic phrase, you should replace them with
straight apostrophes.
You can combine bold and italics by combining the tags, as in ... words...</i></b>.

To create a long string of text in the strings.xml file, enclose the entire text within <string
name="your_string_name">
</string> in the strings.xml file (your_string_name is the name you provide the string resource,
such as article_text ).
Text lines in the strings.xml file don't wrap around to the next line — they extend beyond the right
margin. This is the correct behavior. Each new line of text starting at the left margin represents an
entire paragraph.
Enter \n to represent the end of a line, and another \n to represent a blank line. If you don't add
end-of-line characters, the paragraphs will run into each other when displayed on the screen.
Tip: If you want to see the text wrapped in strings.xml, you can press Return to enter hard line
endings, or format the text first in a text editor with hard line endings. The endings will not be
displayed on the screen.

Referring to a TextView in code


To refer to a TextView in your Java code, use its resource id . For example, to update a
TextView with new text, you would:
1) Find the TextView (with the id show_count ) and assign it to a variable. You use the
findViewById() method of the View class, and refer to the view you want to find using
this format:
R.id.view_id
84
In which view_id is the resource identifier for the view:

mShowCount = (TextView) findViewById(R.id.show_count);

2) After retrieving the view as a TextView member variable, you can then set the text of the text
view to the new text using the setText() method of the TextView class:
mShowCount.setText(mCount_text);

Scrolling views
If the information you want to show in your app is larger than the device's display, you can
create a scrolling view that the user can scroll vertically by swiping up or down, or horizontally
by swiping right or left.
You would typically use a scrolling view for news stories, articles, or any lengthy text that doesn't
completely fit on the display. You can also use a scrolling view to combine views (such as a TextView
and a Button) within a scrolling view.

Creating a layout with a ScrollView


The ScrollView class provides the layout for a vertical scrolling view. (For horizontal scrolling,
you would use HorizontalScrollView.) ScrollView is a subclass of FrameLayout, which means that
you can place only one view as a childwithin it; that child contains the entire contents to scroll.

Even though you can place only one child view inside a ScrollView, the child view could be a
view group with a hierarchy of child views, such as a LinearLayout. A good choice for a view
within a ScrollView is a LinearLayout that is arranged in a vertical orientation.

ScrollView and performance


85
With a ScrollView, all of your views are in memory and in the view hierarchy even if they aren't
displayed on screen. This makes ScrollView useful for smoothly scrolling pages of free-form text,
because the text is already in memory. However, ScrollView can use up a lot of memory, which can
affect the performance of the rest of your app.
Using nested instances of LinearLayout can also lead to an excessively deep view hierarchy, which
can slow down performance. Nesting several instances of LinearLayout that use the
android:layout_weight attribute can be especially expensive as each child view needs to be measured
twice. Consider using flatter layouts such as RelativeLayout or GridLayout to improve performance.
Complex layouts with ScrollView may suffer performance issues, especially with child views such as
images. We recommend that you not use images with a ScrollView. To display long lists of items, or
images, consider using a RecyclerView. Also, using AsyncTask provides a simple way to perform
work outside the main thread, such as loading images in a background thread, then applying them to
the UI once finished. AsyncTask is covered in another chapter.

ScrollView with a TextView

To show a scrollable magazine article on the screen, you might use a RelativeLayout for the
screen that includes a separate TextView for the article heading, another for the article
subheading, and a third TextView for the scrolling article text (see figure below), set within a
ScrollView. The only part of the screen that would scroll would be the ScrollView with the article
text.

ScrollView with a LinearLayout

The ScrollView view group can contain only one view; however, that view can be a view group that
contains views, such as LinearLayout. You can nest a view group such as LinearLayout within the
ScrollView view group, thereby scrolling everything that is inside the LinearLayout.

86
When adding a LinearLayout inside a ScrollView, use match_parent for the LinearLayout's
android:layout_width attribute to match the width of the parent view group (the ScrollView), and use
wrap_content for the LinearLayout's
android:layout_height attribute to make the view group only big enough to enclose its contents and
padding.

Since ScrollView only supports vertical scrolling, you must set the LinearLayout orientation to
vertical (by using the
android:orientation="vertical" attribute), so that the entire LinearLayout will scroll vertically. For
example, the following XML layout scrolls the article TextView along with the article_subheading

87
TextView:

<ScrollView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/article_heading">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/article_subheading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/padding_regular"
android:text="@string/article_subtitle"
android:textAppearance="@android:style/TextAppearance" />
<TextView
android:id="@+id/article"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:lineSpacingExtra="@dimen/line_spacing"
android:text="@string/article_text" />

</LinearLayout>
</ScrollView>

88
4.1 : User Input Controls
Interaction design for user input

The reason you design an app is to provide some function to a user, and in order to use it, there must
be a way for the user to interact with it. For an Android app, interaction typically includes tapping,
pressing, typing, or talking and listening. And the framework provides corresponding user interface
(UI) elements such as buttons, menus, keyboards, text entry fields, and a microphone.
In this chapter you will learn how to design an app's user interaction—the buttons needed for
triggering actions, and the text entry fields for user input. In your design you need to anticipate what
users might need to do, and ensure that the UI has elements that are easy to access, understand, and
use. When your app needs to get data from the user, make it easy and obvious. Give the user
whatever assistance possible to provide any input data, such as anticipating the source of the data,
minimizing the number of user gestures (such as taps and swipes), and pre-filling forms if possible.
Make sure your app is intuitive; that is, your app should perform as your users expect it to perform.
When you rent a car, you expect the steering wheel, gear shift, headlights, and indicators to be in a
certain place. When you enter a room, you expect the light switch to be in a certain place. When a
user starts an app, the user expects buttons to be clickable, spinners to show a drop-down menu, and
text editing fields to show the onscreen keyboard when tapping inside them.
Don't violate the established expectations, or you'll make it harder for your users to use your app.

Note: Android users have become familiar with UI elements acting in a certain way, so it is important
to be consistent with the experience of other Android apps, and predictable in your choices and their
layout. Doing so helps you make apps that satisfy your customers.
This chapter introduces the Android input controls, which are the interactive components in your app's
user interface. You can use a wide variety of input controls in your UI, such as text fields, buttons,
checkboxes, radio buttons, toggle buttons, spinners, and more.

In the above figure:


1. Button
2. Text field
3. Seek bar
4. Checkboxes
5. Radio buttons
6. Toggle
7. Spinner
Input controls and view focus
Android applies a common programmatic abstraction to all input controls called a view. The
View class represents the basic building block for UI components, including input controls. In
previous chapters, we have learned that View is the base class for classes that provide support for
interactive UI components, such as buttons, text fields, and layout managers.

89
If there are many UI input components in your app, which one gets input from the user first? For
example, if you have several TextView objects and an EditText object in your app, which UI
component (that is, which View) receives text typed by the user first?
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. You can define a focus order in which
the user is guided from UI control to UI control using the Return key, Tab key, or arrow keys. Focus
can also be programmatically controlled; a programmer can requestFocus() on any View that is
focusable.

Another attribute of an input control is clickable. If this attribute is (boolean) true , then the View can
react to click events. As it is with focus, clickable can be programmatically controlled.
The difference between clickable and focusable is that clickable means the view can be clicked or
tapped, while focusable means that the view is allowed to gain focus from an input device such as
a keyboard. Input devices like keyboards can't determine which view to send their input events to,
so they send them to the view that has focus.
Android device input methods are becoming quite diverse: directional pads, trackballs, touch screens,
keyboards, and more. Some devices, like tablets and smartphones, are primarily navigated by touch.
Others, like the Google TV, have no touch screen whatsoever and rely upon input devices such as
those with a directional pad (d-pad). When a user is navigating through a user interface with an input
device such as directional keys or a trackball, it is necessary to:
Make it visually clear which view has focus, so that the user knows where the input goes.
Explicitly set the focus in your code to provide a path for users to navigate through the input
elements using directional keys or a trackball.
Fortunately, in most cases you don't need to control focus yourself, unless you want to provide a set
of text input fields and you want the user to be able to move from one field to the next by tapping
the Return or Tab key. Android provides "touch mode" for devices that can be touched, such as
smartphones and tablets. When the user begins interacting with the interface by touching it, only
Views with isFocusableInTouchMode() set to true are focusable, such as text input fields.
Other Views that are touchable, such as buttons, do not take focus when touched. If the user hits a
directional key or scrolls with a trackball, the device exits "touch mode" and finds a view to take
focus.
Focus movement is based on an algorithm that finds the nearest neighbor in a given direction:

When the user touches the screen, the topmost view under the touch is in focus, providing
touch-access for the child views of the topmost view.
If you set an EditText view to a single-line, the user can tap the Return key on the keyboard to
close the keyboard and shift focus to the next input control view based on what the Android
system finds:
The system usually finds the nearest input control in the same direction the user was
navigating (up, down, left, or right).
If there are multiple input controls that are nearby and in the same direction, the system
scans from left to right,
top to bottom.
Focus can also shift to a different view if the user interacts with a directional control, such as a
directional pad (d-pad) or trackball.
You can influence the way Android handles focus by arranging input controls such as EditText
elements in a certain layout from left to right and top to bottom, so that focus shifts from one to the
other in the sequence you want.
If the algorithm does not give you what you want, you can override it by adding the nextFocusleft,
nextFocusRight , and nextFocusUp , nextFocusDown XML attributes to your layout file.

90
1. Add one of these attributes to a view to decide where to go upon leaving the view—in other
words, which view should be the next view.
2. Define the value of the attribute to be the id of the next view. For example:

<LinearLayout
android:orientation="vertical"
... >
<Button android:id="@+id/top"
android:nextFocusUp="@+id/bottom"
... />
<Button android:id="@+id/bottom"
android:nextFocusDown="@+id/top"
... />
</LinearLayout>

Ordinarily in a vertical Linear Layout, navigating up from the first Button would not go anywhere,
nor would navigating down from the second Button. But in the above example, the top Button has
defined the bottom button as the nextFocusUp (and vice versa), so the navigation focus will cycle
from top-to-bottom and bottom-to-top.
If you'd like to declare a View as focusable in your UI (when it is traditionally not), add the
android:focusable XML attribute to the View in the layout, and set its value to true . You can also
declare a View as focusable while in "touch mode" with android:focusableInTouchMode set to true.

You can also explicitly set the focus or find out which view has focus by using the following
methods:

Call onFocusChanged to determine where focus came from.


To find out which view currently has the focus, call Activity.getCurrentFocus(), or use
ViewGroup.getFocusedChild() to return the focused child of a view (if any).
To find the view in the hierarchy that currently has focus, use findFocus().
Use requestFocus to give focus to a specific view.
To change whether a view can take focus, call setFocusable.
To set a listener that will be notified when the view gains or loses focus, use
setOnFocusChangeListener.
Understanding focus with respect to input controls is essential for understanding how the on- screen
keyboard works with text editing views. For example, depending on which attributes you use with
an EditText view, tapping the Return key in the keyboard can either enter a new line, or advance
the focus to the next view.

Using buttons
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.
When touched or clicked, a button performs an action. The text and/or icon provides a hint of that
action. It is also referred to as a "push-button" in Android documentation.

A button is a rectangle or rounded rectangle, wider than it is tall, with a descriptive caption in its center.
Android buttons follow the guidelines in the the Android Material Design Specification—you will learn
more about that in a later lesson.
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.

91
In the above figure:

1. Raised button in three states: normal, disabled, and pressed.


2. Flat button in three states: normal, disabled, and pressed.

Designing raised buttons


A raised button is a rectangle or rounded rectangle that appears lifted from the screen—the shading
around it indicates that it is possible to touch or click it. The raised button can show text or an icon, or
show both text and an icon.
To use raised buttons that conform to the Material Design Specification, follow these steps:
1. In your build.gradle (Module: app) file, add the newest appcompat library to the dependencies
section:

compile 'com.android.support:appcompat-v7:x.x.x.'

In the above, x.x.x. is the version number. If the version number you specified is lower than the
currently available library version number, Android Studio will warn you ("a newer version is
available"). Update the version number to the one Android Studio tells you to use.
2. Make your activity extend android.support.v7.app.AppCompatActivity:

public class MainActivity extends AppCompatActivity {


...

3. Use the Button element in the layout file. There is no need for an additional attribute, as a
raised button is the default style.

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
... />
Use raised buttons to give more prominence to actions in layouts with a lot of varying conte nt.
Raised buttons add dimension to a flat layout—they emphasize functions on busy or wide spaces.
Raised buttons show a background shadow when touched (pressed) or clicked, as shown below.

In the above figure:


1. Normal state: In its normal state, the button looks like a raised button.
2. 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.
3. Pressed state: The pressed state, with a larger background shadow, indicates that the button is
92
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.

Creating a raised button with text


Some raised buttons are best designed as text, without an icon, such as a "Save" button, because an
icon by itself might not convey an obvious meaning. To create a raised button with text, usethe
Button class, which extends the TextView class.
To create a raised button with just text, use the Button class in your XML layout as follows:

<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 betranslated
into French as "Enregistrer" without changing any of the code.

Creating a raised button with an icon and text


While a button usually displays text that tells the user what the button is for, raised buttons
can also display icons along with text.
Choosing an icon
To choose images of a standard icon that are resized for different displays, follow these steps:
1. Expand app > 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 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.

93
94
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 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.

Adding the button with text and icon to the layout


To create a button with text and an icon as shown in the figure below, use a Button in your XML
layout. Add the android:drawableLeft attribute to draw the icon to the left of the button's text, as
shown in the figure below:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="alert"
android:drawableLeft="@drawable/button_icon"
... />

Creating a raised button with only an icon


If the icon is universally understood, you may want to use it instead of text.

<ImageButton

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/button_icon"
... />
To create a raised button with just an icon or image (no text), use the ImageButton class, which
extends the ImageView class. You can add an ImageButton to your XML layout as follows:

Changing the style and appearance of raised buttons


The simplest way to show a more prominent raised button is to use a different background color for
the button. You can specify the android:background attribute with a drawable or color resource:

android:background="@color/colorPrimary"
The appearance of your button—the background color and font—may vary from one device to
another, because devices by different manufacturers often have different default styles for input

95
controls. You can control exactly how your buttons and other input controls are styled using a
theme that you apply to your entire app.
For instance, to ensure that all devices that can run the Holo theme will use the Holo theme for
your app, declare the following in the <application> element of the AndroidManifest.xml file:

android:theme="@android:style/Theme.Holo"
After adding the above declaration, the app will be displayed using the theme.

Apps designed for Android 4.0 and higher can also use the DeviceDefault public theme family.
DeviceDefault themes are aliases for the device's native look and feel. The DeviceDefault theme
family and widget style family offer ways for developers to target the device's native theme with
all customizations intact.
For Android apps running on 4.0 and newer, you have the following options:
Use a theme, such as one of the Holo themes, so that your app has the exact same look across all
Android devices running 4.0 or newer. In this case, the app's look does not change when running
on a device with a different default skin or custom skin.
Use one of the DeviceDefault themes so that your app takes on the look of the device's default
skin. Don't use a theme, but you may have unpredictable results on some devices.
If you're not already familiar with Android's style and theme system, you should read Styles and
Themes. The blog post "Holo Everywhere" provides information about using the Holo theme while
supporting older devices.
For a guide on styling and customizing buttons using XML, see Buttons (in the "User Interface"
section of the Android developer guide). For a comprehensive guide to designing buttons, see
"Components - Buttons" in the Material Design Specification.

Designing flat buttons


A flat button, also known as a borderless button, is a text-only button that appears flat on the
screen without a shadow. The major benefit of flat buttons is simplicity — they minimize distraction
from content. Flat buttons are useful when you have a dialog, as shown in the figure below, which
requires user input or interaction. In this case, you would want to have the same font and style as the
text surrounding the button. This keeps the look and feel the same across all elements within the
dialog.

Flat buttons, shown below, resemble basic buttons except that they have no borders or background,
but still change appearance during different states. A flat button shows an ink shade around it when
pressed (touched or clicked).

In the above figure:


1. Normal state: In its normal state, the button looks just like ordinary text.
2. Disabled state: When the text is grayed out, the button is not active in the app's context.
3. Pressed state: The pressed state, with a background shadow, indicates that the button is being
touched or clicked. When you attach a callback to the button (such as the android:onClick
96
attribute), the callback is called when the button is in this state.
Note: If you use a flat button within a layout, be sure to use padding to set it off from the
surrounding text, so that the user can easily see it.
To create a flat button, use the Button class. Add a Button to your XML layout, and apply "?
android:attr/borderlessButtonStyle" as the style attribute:

<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"
style="?android:attr/borderlessButtonStyle"
/>

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. For
more information about drawable resources, see Drawable Resources in the App Resources section
of the Android Developer Guide.
If you are using multiple images as buttons, arrange them in a viewgroup so that they are grouped
together. For example, the following images in the drawable folder (icecream_circle.jpg,
donut_circle.jpg, and froyo_circle.jpg) are defined for ImageViews that are grouped in a
LinearLayout set to a horizontal orientation so that they appear side-by-side:

97
Designing a floating action button
A floating action button, shown below as #1 in the figure below, is a circular button that appears to
float above the layout.

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

98
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:

compile 'com.android.support:design:23.4.0'

Note: The version number at the end of the statement may change; use the newest version
suggested by Android Studio. 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:
Floating action buttons, by default, are 56 x 56 dp in size. It is best to use the default size unless
<android.support.design.widget.FloatingActionButton 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" />

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"

Responding to button-click events


Use an event listener called OnClickListener, which is an interface in the View class, to
respond to the click event that occurs when the user taps or clicks a clickable object, such as a
Button, ImageButton, or FloatingActionButton. For more information on event listeners, or other
types of UI events, read the Input Events section of the Android Developer Documentation.

Adding onClick to the layout element


To set up an OnClickListener for the clickable object in your Activity code and assign a callback
method, use the android:onClick attribute with the clickable object's element in the XML layout.
For example:

<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />

In this case, when a user clicks the button, the Android system calls the Activity's sendMessage()
method:

public void sendMessage(View view) {


// Do something in response to button click
}

The method you declare as the android:onClick attribute must be public , return void , and define
a View as its only parameter (this will be the view that was clicked). Use the method to perform
a task or call other methods as a response to the button click.
99
Using the button-listener design pattern
You can also handle the click event programmatically using the button-listener design
pattern (see figure below).

Use the event listener View.OnClickListener, which is an interface in the View class that contains
a single callback method, onClick(). The method is called by the Android framework when the view
is triggered by user interaction.
The event listener must already be registered to the view in order to be called for the event. Follow
these steps to register the listener and use it (refer to the figure below the steps):
1. Use the findViewById() method of the View class to find the button in the XML layout file:

Button button = (Button) findViewById(R.id.button_send);

2. Get a new View.OnClickListener object and register it to the button by calling the
setOnClickListener () method. The argument to setOnClickListener() takes an object that
implements the View.OnClickListener interface, which has one method: onClick().
button.setOnClickListener(new View.OnClickListener() {
...

3. Define the onClick() method to be public , return void , and define a View as its onlyparameter:
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.
5. To set the click listener programmatically instead of with the onClick attribute, customize the
View.OnClickListener class and override its onClick() handler to perform some action, as shown
below:

fab.setOnClickListener(new View.OnClickListener() { @Override


public void onClick(View view) {
// Add a new word to the wordList.
}
});

Using the event listener interface for other events


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

100
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 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.
Example: Source code:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:gravity="center"
android:text="HELLO WORLD"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Change font size"
android:textSize="20sp" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Change color"
android:textSize="20sp" />
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Change font"
android:textSize="20sp" />
</LinearLayout>

101
Java file
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AndroidActivity extends Activity {
float font =24;
int i=1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView t1=(TextView) findViewById(R.id.textView1);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
t1.setTextSize(font);
font=font+4;
if(font==40)
font=20;
}
});
Button b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
switch(i)
{
case 1:
t1.setTextColor(Color.parseColor("#0000FF"));
break;
case 2:
t1.setTextColor(Color.parseColor("#00FF00"));
break;
case 3:
t1.setTextColor(Color.parseColor("#FF0000"));
break;
case 4:
t1.setTextColor(Color.parseColor("#800000"));
break;
}
i++;
if(i==5)
i=1;
}
});
}
}

Example: Develop a native calculator application.

Source code & Steps::

Main.xml coding
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
102
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout1"
android:layout_marginLeft="10pt"
android:layout_marginRight="10pt"
android:layout_marginTop="3pt">
<EditText
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginRight="5pt"
android:id="@+id/etNum1"
android:layout_width="match_parent"
android:inputType="numberDecimal">
</EditText>
<EditText
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5pt"
android:id="@+id/etNum2"
android:layout_width="match_parent"
android:inputType="numberDecimal">
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout2"
android:layout_marginTop="3pt"
android:layout_marginLeft="5pt"
android:layout_marginRight="5pt">
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="+"
android:textSize="15pt"
android:id="@+id/btnAdd">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="-"
android:textSize="15pt"
android:id="@+id/btnSub">
</Button>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_weight="1"
android:text="*"
android:textSize="15pt"
android:id="@+id/btnMult">
</Button>
<Button
android:layout_height="wrap_content"
103
android:layout_width="match_parent"
android:layout_weight="1"
android:text="/"
android:textSize="15pt"
android:id="@+id/btnDiv">
</Button>
</LinearLayout>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="5pt"
android:layout_marginRight="5pt"
android:textSize="12pt"
android:layout_marginTop="3pt"
android:id="@+id/tvResult"
android:gravity="center_horizontal">
</TextView>
</LinearLayout>

MainActivity.java file
package CALCU.CALU;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class CALCULATORActivity extends Activity implements
OnClickListener {
EditText input1;
EditText input2;
Button addition;
Button subtraction;
Button multiplication;
Button division;
TextView tvResult;
String oper = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
input1 = (EditText) findViewById(R.id.etNum1);
input2 = (EditText) findViewById(R.id.etNum2);
addition = (Button) findViewById(R.id.btnAdd);
subtraction = (Button) findViewById(R.id.btnSub);
multiplication = (Button) findViewById(R.id.btnMult);
division = (Button) findViewById(R.id.btnDiv);
tvResult = (TextView) findViewById(R.id.tvResult);
// set a listener
addition.setOnClickListener(this);
subtraction.setOnClickListener(this);
multiplication.setOnClickListener(this);
division.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
104
float num1 = 0;
float num2 = 0;
float result = 0;
// check if the fields are empty
if (TextUtils.isEmpty(input1.getText().toString())
|| TextUtils.isEmpty(input2.getText().toString())) {
return;
}
// read EditText and fill variables with numbers
num1 = Float.parseFloat(input1.getText().toString());
num2 = Float.parseFloat(input2.getText().toString());
// defines the button that has been clicked and performs the
corresponding operation
// write operation into oper, we will use it later for output
switch (v.getId()) {
case R.id.btnAdd:
oper = "+";
result = num1 + num2;
break;
case R.id.btnSub:
oper = "-";
result = num1 - num2;
break;
case R.id.btnMult:
oper = "*";
result = num1 * num2;
break;
case R.id.btnDiv:
oper = "/";
result = num1 / num2;
break;
default:
break;
}
// form the output line
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + result);} }

Using input controls for making choices


Android offers ready-made input controls for the user to select one or more choices:

Checkboxes: Select one or more values from a set of values by clicking each value's checkbox.
Radio buttons: Select only one value from a set of values by clicking the value's circular
"radio" button. If you are providing only two or three choices, you might want to use radio
buttons for the choices if you have room in your layoutfor them.
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.

105
Users expect checkboxes to appear in a vertical list, like a to-do list, or side-by-side horizontally if
the labels are short.

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>

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();

106
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:

Tip: To respond quickly to a checkbox—such as display a message (like an alert), or show a set of
further options—you can use the android:onClick attribute in the XML layout for each

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));
}
...
}

checkbox to declare the callback method for that checkbox, which must be defined within the
activity that hosts this layout.
For more information about checkboxes, see Checkboxes in the User Interface section of the
Android Developer Documentation.

Radio buttons

Use radio buttons when you have two or more options that are mutually exclusive—the user must
select only one of them.
(If you want to enable more than one selection from the set, use checkboxes.)

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 instance 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:

107
<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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/next_day_ground_delivery"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/pickup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pick_up"
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. 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;
}

Tip: To give users a chance to review their radio button selection before the app responds, you could
implement a Submit or Done button as shown previously with checkboxes, and remove the
android:onClick attributes from the radio buttons. Then add the onRadioButtonClicked() method to
the android:onClick attribute for the Submit or Done button.
For more information about radio buttons, see "Radio Buttons" in the User Interface section of the
Android Developer Documentation.

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".

108
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.

Using a toggle button


Create a toggle button by using a ToggleButton element in your XML layout:
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/my_toggle" android:text="
android:onClick="onToggleClick"/>

Tip: The android:text attribute does not provide a text label for a toggle button—the toggle button
always shows either "ON" or "OFF". To provide a text label next to (or above) the toggle button,
use a separate TextView .
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 bycalling
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? ");
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();
}
});
}

Tip: You can also programmatically change the state of a ToggleButton using the
setChecked(boolean) method. Be aware, however, that the method specified by the
android:onClick() attribute will not be executed in this case.
Example:

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


<RelativeLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
android:layout_width="match_parent" android:layout_height=
"match_parent">
<ToggleButton
android:id="@+id/toggle1"
android:layout_width="wrap_content"

109
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="120dp"
android:checked="true"
android:textOff="OFF"
android:textOn="ON"/>
<ToggleButton
android:id="@+id/toggle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/toggle1"
android:layout_toRightOf="@+id/toggle1"
android:textOff="OFF"
android:textOn ="ON"/>
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:layout_marginTop="200dp"
android:text="Submit" />
</RelativeLayout>

Java File
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ToggleButton tb1 =
(ToggleButton)findViewById(R.id.toggle1);
final ToggleButton tb2 =
(ToggleButton)findViewById(R.id.toggle2);
Button btnGet = (Button)findViewById(R.id.getBtn);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Toggle
Button1 - " + tb1.getText().toString() + " \n" + "Toggle
Button2 -
" + tb2.getText().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"
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:

110
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

public void onSwitchClick(View view) {


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();
}
});
}

switch is on or off, and displays a toast message:

Tip: You can also programmatically change the state of a Switch using the setChecked(boolean)
method. Be aware, however, that the method specified by the android:onClick() attribute will not be
executed in this case.

Spinners
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. However, scrolling a long list (such
as a list of countries) is not recommended as it can be hard to select an item.
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.

111
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


You add an adapter that fills the spinner list with values. 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.
The spinner-adapter pattern takes the data set you've specified and makes a view for each item in the
data set, as shown in the figure below.

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>

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);
} 112
}
4. Also in the onCreate() method, add a statement that creates the ArrayAdapter with the string
array:
As shown above, you use the createFromResource() method, which takes as arguments:
// 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. The activity that implements the callbacks for processing the results of the spinner ( this)
6. The array ( labels_array )
7. The layout for each spinner item ( layout.simple_spinner_item ).

Tip: You should use the simple_spinner_item default layout, unless you want to define your
own layout for the items in the spinner.
8. 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);

Tip: You should use the simple_spinner_dropdown_item default layout, unless you want to define
your own layout for the spinner's appearance.
9. Use setAdapter() to apply the adapter to the spinner:

// Apply the adapter to the spinner.


spinner.setAdapter(adapter);

The full code for the onCreate() method is shown below:

@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);
}
// 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);
}
}

113
Implement the OnItemSelectedListener interface in the Activity
To define the selection callback for the spinner, update the Activity that uses the spinner to
implement the AdapterView.OnItemSelectedListener interface:
Android Studio automatically imports the AdapterView widget. Implement the
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener {

AdapterView.OnItemSelectedListener interface in order to have the onItemSelected() and


onNothingSelected() callback methods to use with the spinner object.
When the user chooses an item from the spinner's drop-down list, here's what happens and how you
retrieve the item:
1. The Spinner object receives an on-item-selected event.
2. The event triggers the calling of the onItemSelected() callback method of the
AdapterView.OnItemSelectedListener interface.
3. Retrieve the selected item in the spinner menu using the getItemAtPosition() method of the
AdapterView class:

public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id)
{
String spinner_item = adapterView.getItemAtPosition(pos).toString();
}
The arguments for onItemSelected() are as follows:
parent AdapterView The AdapterView where the selection happened

view View The view within the AdapterView that was clicked

int pos The position of the view in the adapter

long id The row id of the item that is selected

4. Implement/override the onNothingSelected() callback method of the


AdapterView.OnItemSelectedListener interface to do something if nothing is selected.

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.

114
Note: In the above figure, #1 is the Return (also known as Enter) key.

Enabling Return to advance to the next view


If you add the android:inputType attribute to the EditText view with a value such as
"textCapCharacters" (to change the input to all capital letters) or "textAutoComplete" (to
enable spelling suggestions as the user types), tapping the Return key closes the on-screen
keyboard and advances the focus to the next view. This behavior is useful if you want the user
to fill out a form consisting of EditText fields, so that the user can advance quickly to the next
EditText view.

Attributes for customizing an EditText view


Use attributes to customize the EditText view for input. For example:
android:maxLines="1" : Set the text entry to show only one line.
android:lines="2" : Set the text entry to show 2 lines, even if the length of the text is less.
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".


For a list of EditText attributes, including inherited TextView attributes, see the "Summary" of the
EditText class description.

Getting the user's input


Enabling the user to input text is only useful if you can use that text in some way in your app. To
use the input, you must first get it from the EditText view in the XML layout. The steps youfollow
to set up the EditText view and get user input from it are:
1. Create the EditText view element in the XML layout for an activity. Be sure to identify this
element with an android:id
so that you can refer to it by its id :
android:id="@+id/editText_main"

2. In the Java code for the same activity, create a method with a View parameter that gets the
EditText editText = (EditText) findViewById(R.id.editText_main);
115
EditText object (in the example below, editText ) for the EditText view, using the
findViewById() method of the View class to find the view by its id ( editText_main):
3. Use the getText() method of the EditText class (inherited from the TextView class) to obtain
the text as a character sequence (CharSequence). You can convert the character sequence
into a string using the toString() method of the CharSequence class, whichreturns a 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.

Changing keyboards and input behaviors


The Android system shows an on-screen keyboard—known as a soft input method—
when a text field in the UI receives focus. To provide the best user experience, you can specify
characteristics about the type of input the app expects, such as whether it's a phone number or
email address. You can also specify how the input method should behave, such as whether ornot
it shows spelling suggestions or provides capital letters for the beginning of a sentence. You can
change the soft input method to a numeric keypad for entering only numbers, or even a phone
keypad for phone numbers.
Android also provides an extensible framework for advanced programmers to develop and install
their own Input Method Editors (IME) for speech input, specific types of keyboard entry, and
other applications.
Declare the input method by adding the android:inputType attribute to the EditText view. For
example, the following attribute sets the on-screen keyboard to be a phone keypad:

android:inputType="phone"

Use the android:inputType attribute with the following values:


textCapSentences : Set the keyboard to capital letters at the beginning of a sentence.
textAutoCorrect : Enable spelling suggestions as the user types.
textPassword : Turn each character the user enters into a dot to conceal an entered password.
textEmailAddress : For email entry, show an email keyboard with the "@" symbol
conveniently located next to the space key.
phone : For phone number entry, show a numeric phone keypad.

Tip: You can use the pipe (| ) character (Java bitwise OR) to combine attribute values for the
android:inputType
attribute:

android:inputType="textAutoCorrect|textCapSentences"

For details about the android:inputType attribute, see Specifying the Input Method Type in the
developer documentation. For a complete list of constant values for android:inputType, see the
"android:inputType" section of the TextView documentation.

Changing the "action" key in the keyboard


On Android devices, the "action" key is the Return key. This key is normally used to enter
another line of text for an EditText element that allows multiple lines. If you set an
android:inputType attribute for the EditText view with a value such as "textCapCharacters" (to
change the input to all capital letters) or "textAutoComplete" (to enable spelling suggestions as
the user types), the Return key closes the on-screen keyboard and advances the focus to the next
view.
If you want the user to enter something other than text, such as a phone number, you may want
to change the "action" key to an icon for a Send key, and change the action to be dialing a phone
number. Follow these steps:
116
1. Use the android:inputType attribute to set an input type for the keyboard:

<EditText
android:id="@+id/phone_number" android:inputType="phone"
... >
</EditText>
The android:inputType attribute, in the above example, sets the keyboard type to phone ,
which forces one line of input (for a phone number).
2. Use setOnEditorActionListener() to set the listener for the EditText view to respond to the use
of the "action" key:

EditText editText = (EditText) findViewById(R.id.phone_number);


editText.setOnEditorActionListener(new
TextView.OnEditorActionListener() {
@Override
// Add onEditorAction()
public method
boolean onEditorAction(TextView textView,
}
int actionId, KeyEvent keyEvent) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) { dialNumber();
3. Use the IME_ACTION_SEND
handled = true; constant in the EditorInfo class for the actionId to show a Send
key
} as the "action" key, and create a method to respond to the pressed Send key (in this case,
return handled;
dialNumber to dial the entered phone number):
});

117
Date and time pickers
Android provides ready-to-use 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. To learn about
fragments, see Fragments in the API Guide.
One benefit of using fragments for the pickers is that you can isolate the code sections for managing
the date and the time after the user selects them from the pickers. You can also use DialogFragment
to manage the dialog lifecycle.
Tip: Another benefit of using fragments for the pickers is that you can implement different layout
configurations, such as a basic dialog on handset-sized displays or an embedded part of a layout on
large displays.

Methods of DatePicker
Let‘s discuss some common methods of a datepicker which are used to configure a DatePicker in
our application.
1. setSpinnersShown(boolean shown):
This method is used to set whether the spinner of the date picker in shown or not. In this method
you have to set a Boolean value either true or false. True indicates spinner is shown, false value
indicates spinner is not shown. Default value for this function is true.
Below we show the use of setSpinnerShown() function by setting false value.
2. getDayOfMonth():
This method is used to get the selected day of the month from a date picker. This method returns
an integer value.
Below we get the selected day of the month from a date picker.
/*Add in Oncreate() funtion after setContentView()*/

Prepared by Mrs.V.R.Sonar 118


V.R.Sonar
DatePicker simpleDatePicker = (DatePicker) findViewById(R.id.simpleDatePicker);
// initiate a date picker
int day = simpleDatePicker.getDayOfMonth(); // get the selected day of the month
3. getMonth():
This method is used to get the selected month from a date picker. This method returns an integer
value.
Below we get the selected month from a date picker.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a da
te picker
int month = simpleDatePicker.getMonth(); // get the selected month
4. getYear():
This method is used to get the selected year from a date picker. This method returns an integer
value.
Below code is used to get the selected year from a date picker.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a da
te picker
int year = simpleDatePicker.getYear(); // get the selected year
5. getFirstDayOfWeek():
This method is used to get the first day of the week. This method returns an integer value.
Below code is used to get the first day of the week.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a da
te picker

int firstDay=simpleDatePicker.getFirstDayOfWeek(); // get the first day of the week

Attributes of DatePicker
Now let‘s we discuss some important attributes that helps us to configure a DatePicker in your
XML file (layout).
1. id: id is an attribute used to uniquely identify a date picker.
<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
2. datePickerMode: This attribute is used to set the Date Picker in mode either spinner or
calendar. Default mode is calendar but this mode is not used after api level 21, so from api level
21 you have to set the mode to spinner.
Below is an example code in which we set the mode to spinner for a date picker.
<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner" /> <!-- spinner mode of a date picker -->
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a da
te picker
int year = simpleDatePicker.getYear(); // get the selected year

Prepared by Mrs.V.R.Sonar 119


V.R.Sonar
5. getFirstDayOfWeek():
This method is used to get the first day of the week. This method returns an integer value.
Below code is used to get the first day of the week.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a da
te picker

int firstDay=simpleDatePicker.getFirstDayOfWeek(); // get the first day of the week

Attributes of DatePicker
Now let‘s we discuss some important attributes that helps us to configure a DatePicker in your
XML file (layout).
1. id: id is an attribute used to uniquely identify a date picker.
<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
2. datePickerMode: This attribute is used to set the Date Picker in mode either spinner or
calendar. Default mode is calendar but this mode is not used after api level 21, so from api level
21 you have to set the mode to spinner.
Below is an example code in which we set the mode to spinner for a date picker.
<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner" /> <!-- spinner mode of a date picker -->
<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:background="#f00"/> <!-- red color for the background of the date picker -->
Setting background of DatePicker In Java Class:
DatePicker simpleDatePicker=(DatePicker)findViewById(R.id.simpleDatePicker); // initiate a dat
e picker
simpleDatePicker.setBackgroundColor(Color.RED); // red color for the background of a date pick
er
4. padding: padding attribute is used to set the padding from left, right, top or bottom for a date
picker.
 paddingRight: set the padding from the right side of the date picker.
 paddingLeft: set the padding from the left side of the date picker.
 paddingTop: set the padding from the top side of the date picker.
 paddingBottom: set the padding from the bottom side of the date picker.
 Padding: set the padding from the all side‘s of the date picker.
Below code of padding attribute set the 40dp padding from all the side‘s of the date picker.
<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
Prepared by Mrs.V.R.Sonar 120
V.R.Sonar
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:padding="40dp"/> <!-- 40dp padding from all the sides of a date picker -->

Example 1:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#150"
android:datePickerMode="spinner" />

<Button
android:id="@+id/submitButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/simpleDatePicker"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:background="#150"
android:text="SUBMIT"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>

import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
import android.os.Bundle;

Prepared by Mrs.V.R.Sonar 121


V.R.Sonar
public class MainActivity extends AppCompatActivity {
DatePicker simpleDatePicker;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate the date picker and a button
simpleDatePicker = (DatePicker) findViewById(R.id.simpleDatePicker);
submit = (Button) findViewById(R.id.submitButton);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// get the values for day of month , month and year from a date picker
String day = "Day = " + simpleDatePicker.getDayOfMonth();
String month = "Month = " + (simpleDatePicker.getMonth() + 1);
String year = "Year = " + simpleDatePicker.getYear();
// display the values by using a toast
Toast.makeText(getApplicationContext(), day + "\n" + month + "\n" + year, Toast.LEN
GTH_LONG).show();
}
});

Example 2:

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
tools:context=".MainActivity">

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_date"
android:layout_marginTop="82dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

Prepared by Mrs.V.R.Sonar 122


V.R.Sonar
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT DATE"
android:id="@+id/btn_date"
android:layout_alignBottom="@+id/in_date"
android:layout_toRightOf="@+id/in_date"
android:layout_toEndOf="@+id/in_date" />

<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_time"
android:layout_below="@+id/in_date"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT TIME"
android:id="@+id/btn_time"
android:layout_below="@+id/btn_date"
android:layout_alignLeft="@+id/btn_date"
android:layout_alignStart="@+id/btn_date" />

</RelativeLayout>

package com.dummies.datetimepicker;

import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements


View.OnClickListener {

Button btnDatePicker, btnTimePicker;


EditText txtDate, txtTime;
private int mYear, mMonth, mDay, mHour, mMinute;

@Override
protected void onCreate(Bundle savedInstanceState) {
Prepared by Mrs.V.R.Sonar 123
V.R.Sonar
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnDatePicker=(Button)findViewById(R.id.btn_date);
btnTimePicker=(Button)findViewById(R.id.btn_time);
txtDate=(EditText)findViewById(R.id.in_date);
txtTime=(EditText)findViewById(R.id.in_time);

btnDatePicker.setOnClickListener(this);
btnTimePicker.setOnClickListener(this);

@Override
public void onClick(View v) {

if (v == btnDatePicker) {

// Get Current Date


final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);

DatePickerDialog datePickerDialog = new DatePickerDialog(this,


new DatePickerDialog.OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
if (v == btnTimePicker) {

// Get Current Time


final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);

// Launch Time Picker Dialog


TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {

txtTime.setText(hourOfDay + ":" + minute);


Prepared by Mrs.V.R.Sonar 124
V.R.Sonar
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
}
}

Android Toast with Examples


In android, Toast is a small popup notification that is used to display an information about the operation which we
performed in our app. The Toast will show the message for a small period of time and it will disappear automatically
after a timeout.

Generally, the size of Toast will be adjusted based on the space required for the message and it will be displayed on
the top of the main content of activity for a short period of time.

For example, some of the apps will show a message like “Press again to exit” in toast, when we pressed a back
button on the home page or showing a message like “saved successfully” toast when we click on the button to save
the details.

Following is the pictorial representation of using Toast in android applications.

Create a Toast in Android


In android, we can create a Toast by instantiating an android.widget.Toast object using makeText() method.
The makeText() method will take three parameters: application context, text message and the duration for the toast.
We can display the Toast notification by using show() method.

Following is the syntax of creating a Toast in android applications.

Toast.makeText(context, "message", duration).show();


If you observe above syntax, we defined a Toast notification using makeText() method with three parameters, those
are

Parameter Description

context It’s our application context.

message It’s our custom message which we want to show in Toast notification.

duration It is used to define the duration for notification to display on the screen.

Prepared by Mrs.V.R.Sonar 125


V.R.Sonar
We have two ways to define the Toast duration, either in LENGTH_SHORT or LENGTH_LONG to display the toast
notification for a short or longer period of time.

Following is the example of defining a Toast in android applications.

Toast.makeText(MainActivity.this, "Details Saved Successfully.", Toast.LENGTH_SHORT).s


how();
Now we will see how to implement a Toast notification in android applications with examples.

Android Toast Notification Example


Create a new android application using android studio and give names as ToastExample. In case if you are not aware
of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml
<?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" >

<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Toast"
android:layout_marginTop="200dp" android:layout_marginLeft="140dp"/>
</LinearLayout>
If you observe above code we created a one Button control in XML Layout file to show the toast notification when we
click on Button.

Once we are done with creation of layout with required controls, we need to load the XML layout resource from
our activity onCreate() callback method, for that open
main activity file MainActivity.java from \java\com.tutlane.toastexample path and write the code like as shown
below.

MainActivity.java
package com.tutlane.toastexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
Prepared by Mrs.V.R.Sonar 126
V.R.Sonar
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "You Clicked on Button..", Toast.LEN
GTH_SHORT).show();
}
});
}
}
If you observe above code we are created a toast notification using makeText() method and showing a toast
notification on Button click.

Generally, during the launch of our activity, onCreate() callback method will be called by android framework to get
the required layout for an activity.

Output of Android Toast Notification Example


When we run the above example using an android virtual device (AVD) we will get a result like as shown below.

If you observe the above result we created a toast notification and shown it on Button click based on our
requirements.

Prepared by Mrs.V.R.Sonar 127


V.R.Sonar
Change the Position of Android Toast Notification
By default, the android Toast notification will always appear near the bottom of the screen, centered horizontally like
as shown in the above image.

In case if we want to change the position of Toast notification, we can do it by using the setGravity(int, int,
int) method. The setGravity() method will accept three parameters: a Gravity constant, an x-position offset, and a y-
position offset.

Following is the example of changing the position of android Toast notification to top-right based on offset positions
by using setGravity() method.

Toast toast = Toast.makeText(MainActivity.this, "You Clicked on Button..", Toast.LENG


TH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.RIGHT, 100, 250);
toast.show();
If you want to move the position of toast to right, increase the value of the second parameter. To move it down,
increase the value of the last parameter.

Android Toast Positioning Example


Following is the example of changing the position of android toast notification to top-right side
using setGravity() method.

We need to modify our main activity file MainActivity.java code like as shown below.

MainActivity.java
package com.tutlane.toastexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//display toast message in top right side
Toast toast = Toast.makeText(MainActivity.this, "You Clicked on Button.
.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.RIGHT, 100, 250);
toast.show();
Prepared by Mrs.V.R.Sonar 128
V.R.Sonar
}
});
}
}
If you observe above code we are changing the position of android toast notification using setGravity() property.

Output of Android Toast Positioning Example


When we run above example using android virtual device (AVD) we will get a result like as shown below.

Android Custom Toast with Examples


In android, Toast is a small popup notification that is used to display information about the operation which we
performed in our app. The Toast will show the message for a small period of time and it will disappear automatically
after a timeout.

Generally, the size of Toast will be adjusted based on the space required for the message and it will be displayed on
the top of the main content of activity for a short period of time.

To know more about creation of Toast in android applications, check this Android Toast with Examples.

Generally, the Toast notification in android will be displayed with simple text like as shown in above image. In android,
we can customize the layout of our toast notification to change the appearance of based on requirements like include
images in toast notification or change the background color of toast notification, etc.

Prepared by Mrs.V.R.Sonar 129


V.R.Sonar
Following is the pictorial representation of using Custom Toast notification in android applications.

To customize the appearance of Toast notification, we need to create a custom layout in our XML or application code
and pass the root View object to the setView(View) method.

Create a Custom Toast in Android


To create a custom Toast notification in android, we need to define a custom View layout in XML, for that create a
custom XML file (custom_toast.xml) in layout (/layout) folder and write the code like as shown below.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#80CC28">
<ImageView android:src="@drawable/ic_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<TextView android:id="@+id/txtvw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:textColor="#FFF"
android:textStyle="bold"
android:textSize="15dp" />
</LinearLayout>
To use this custom layout as Toast notification in our android application, we need to inflate the layout using
following code.

LayoutInflater inflater = getLayoutInflater();


View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.cu
stom_toast_layout));
TextView tv = (TextView) layout.findViewById(R.id.txtvw);
Prepared by Mrs.V.R.Sonar 130
V.R.Sonar
tv.setText("Custom Toast Notification");
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
If you observe above code, we created an instance of LayoutInflater with getLayoutInflater(), and then inflate our
XML layout using inflate(int, ViewGroup). Here the first parameter is the layout resource ID and the second is
the root View and this inflated layout will help us to find the View objects in the layout. After that we created a
new Toast with Toast(Context) and set required properties of the toast, then we call setView(View) and pass it to
the inflated layout.

Once we are done with required configurations, then we can show the custom toast notification by
calling show() method.

Now we will see how to implement a custom Toast notification in android applications with examples.

Android Custom Toast Example


Create a new android application using android studio and give names as ToastExample. In case if you are not aware
of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below.

activity_main.xml
<?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" >

<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Custom Toast"
android:layout_marginTop="150dp" android:layout_marginLeft="110dp"/>
</LinearLayout>
If you observe above code we created a one Button control in XML Layout file to show the custom
toast notification when we click on Button.

Now we need to create a custom layout for our toast notification, for that create a new XML file (custom_toast.xml)
in /layout folder and write the code like as shown below.

Custom_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
Prepared by Mrs.V.R.Sonar 131
V.R.Sonar
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#80CC28">
<ImageView android:src="@drawable/ic_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<TextView android:id="@+id/txtvw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:textColor="#FFF"
android:textStyle="bold"
android:textSize="15dp" />
</LinearLayout>
If you observe above code we are loading image (ic_notification) from drawable folder so you need to add your icon
in drawable folder to show it in notification.

Once we are done with the creation of layout with required controls, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.vrs.toastexample path and write the code like as shown below.

MainActivity.java
package com.vrs.customtoastexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) find
ViewById(R.id.custom_toast_layout));
TextView tv = (TextView) layout.findViewById(R.id.txtvw);
tv.setText("Custom Toast Notification");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 100);
toast.setDuration(Toast.LENGTH_LONG);

Prepared by Mrs.V.R.Sonar 132


V.R.Sonar
toast.setView(layout);
toast.show();
}
});
}
}
If you observe above code we are calling our custom toast notification by using LayoutInflater object and showing a
toast notification on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework
to get the required layout for an activity.

Output of Android Custom Toast Example


When we run above example using an android virtual device (AVD) we will get a result like as shown below.

Progress Bar In Android –


Progress bar is a user interface control that shows the progress of any operation. The operation includes
downloading a file, copying a file or moving a file. It is like a graphical representation of an indicator
that shows the progress of some process or operation. Basically, it displays how much completion of
a task has taken place. A progress bar plays a very important role in providing an interactive and user-
friendly interface.
We can define a progress bar in the layout file as-
<ProgressBar
android:id="@+id/p_Bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:max="100"
android:progress="0" />
Prepared by Mrs.V.R.Sonar 133
V.R.Sonar
Attributes Of Progress bar in Android
 android: id– It uniquely identifies the progress bar.
 android: minHeight– It sets the height of the progress bar.
 android: minWidth– It sets the width of the progress bar.
 android: max– It sets the maximum value of the progress bar.
 android: progress– It sets the default progress of the progress bar, which can be set from 0 to
max.
 android:interpolar– It is used to set an acceleration curve for the indeterminate progress bars.
 android: min– It defines the minimum value for the progress bar.
 android: progressTint– It applies Tint on progress indicator in the progress bar.
 android: indeterminate– It sets whether the progress bar is Determinate or Indeterminate.
For this, there are two possible values that are True or False.
 android: animationResolution– It sets the timeout between frames of animation. Timeout is set
in milliseconds.
Methods of Progress Bar
There are certain methods of Android Progress Bar, out of which the most used and important
methods are listed below:
1. getMax()– It returns the maximum value that can be there in the progress bar.
2. incrementProgressBy(int increment_value)– It increments the progress in the bar with the
increment value that is passed in its parameter.
3. setIndeterminate(boolean indeterminate)– It sets the progress bar to be either determinate or
indeterminate. Passing ‘true’ means Indeterminate and passing ‘false’ means Determinate.
4. setMax(int max_value)– It sets the maximum value of the progress in the progress bar.
5. setProgress(int prog_val)– It updates the progress to the progress value that is passed in it.
6. show(Context context, CharSequence title, CharSequence msg)– It displays the progress bar.
It is a static method.
Types of Progress Bar in Android
These progress bars can be of different types like spinner wheel, determinate, and indeterminate. We
will see these one by one-
Spinning Wheel Progress Bar
This one is android’s default progress bar. We define it by writing the following code:
<ProgressBar
android:id="@+id/p_Bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progress="50"/>
Horizontal Progress Bar
Prepared by Mrs.V.R.Sonar 134
V.R.Sonar
We will define horizontal progress bar, and to define it we write the following code.
style="?android:attr/progressBarStyleHorizontal"
It is of two types that are:
i) Determinate Progress Bar
This progress bar is used when we know how long the operation will take place. In this, the actual
progress of the operation is shown. For this, we set –
android:indeterminate="false"
And the actual definition would be as follows:
<ProgressBar
android:id="@+id/p_Bar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="100"
android:progress="0" />
ii) Indeterminate Progress Bar
This progress bar is used when we do not know for how long the operation will take place. In this,
the actual progress is not indicated but it indicates that the progress is taking place. For this, we set –
android:indeterminate="true"
And the actual definition would be as follows:
<ProgressBar
android:id="@+id/p_Bar2"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:max="100"
android:progress="0" />

These three progress bars are shown below :

Prepared by Mrs.V.R.Sonar 135


V.R.Sonar
Implementation of Android Progress Bar
Now we will move towards the implementation of the same. For this, we will follow the steps
below:
1. First of all, we will create a new project and name it. I have named my project “My ProgressBar”.
2. Now we will write the code for the layout, in the activity_main.xml file.
<?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">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="90dp"
ad
android:layout_marginTop="80dp"
android:fontFamily="@font/alegreya_sc_bold"
android:text="Vrs "
android:textColor="#00574B"
android:textSize="50dp" />
Prepared by Mrs.V.R.Sonar 136
V.R.Sonar
<ProgressBar
android:id="@+id/p_Bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:indeterminate="false"
android:max="100"
android:minWidth="200dp"
android:minHeight="50dp"
android:progress="0" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/p_Bar"
android:layout_alignLeft="@+id/p_Bar" />
<TextView
android:id="@+id/txtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="180dp"
android:text="See Your Progress Here..." />
<Button
android:id="@+id/show_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Start" />
</RelativeLayout>
3. After this, open the MainActivity.java file, and write the following code:
package com.Vrs

.myprogressbar;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
Prepared by Mrs.V.R.Sonar 137
V.R.Sonar
public class MainActivity extends AppCompatActivity {
private ProgressBar pbar;
private int a = 0;
private TextView textView;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.tv);
pbar = findViewById(R.id.p_Bar);
Button button = findViewById(R.id.show_btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
a = pbar.getProgress();
new Thread(new Runnable() {
public void run() {
while (a < 100) {
a += 1;
handler.post(new Runnable() {
public void run() {
pbar.setProgress(a);
textView.setText(a + "/" + pbar.getMax());
if (a == 100)

textView.setText(" Your Progess has been Completed");


}
});
try {
// Sleep for 50 ms to show progress you can change it as well.
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
}
4. Finally, we will run the app and it will be as given below-

Prepared by Mrs.V.R.Sonar 138


V.R.Sonar
i) Initially it will be this-
ii) Then we will tap start.
iii) We can see the progress now-
iv) Once it finishes, we can see it as –

Prepared by Mrs.V.R.Sonar 139


V.R.Sonar

You might also like