Chapter 3 - 4 Notes New
Chapter 3 - 4 Notes New
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.
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:
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.
When the selection is the ―Android‖ mode, the default files and folders shown in Figure
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).
Fig. 3.2.10 Selecting the target for running our first app
Activities
Services
Intent and broadcast receivers
Content Providers
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
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:
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:
Figure3.3.3 : ViewGroup objects form branches in the layout and contain other View objects.
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
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
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
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>
<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
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 3"
android:paddingTop="10px"/>
</LinearLayout>
Output:
<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
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:
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">
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"
<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 :
<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:
<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
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"
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"
android:textColor="@android:color/white"
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.)
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.
Menus. You can use an XML resource file to define menu items and store them in your
project in the menu folder.
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:
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.
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
Since you had already associated mShowCount with the TextView for displaying the count, the
mShowCount.setText() method updates the text view on the screen
<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.
<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>
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:
<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.
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:
<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" />
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Output:
Example:
activity_main.xml
</TableRow>
</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.
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-->
android:id="@+id/firstRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<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>
2. when android:stretchColumns="2"
3. when android:stretchColumns="*"
</TableRow>
</TableLayout>
<!-- 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" />
MainActivity.java
package com.vrs.linearlayout;
import android.support.v7.app.AppCompatActivity;
PREPARED BY MRS. V.R.SONAR 65
import android.os.Bundle;
<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">
<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>
<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
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"
/>
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"
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"
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"
/>
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"
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-->
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"
/>
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.
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.
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"
/>
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.
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;
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
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
<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:autoLink="web"
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.
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.
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.
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.
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.
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:
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:
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:
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.
<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.
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.
<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:
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.
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).
<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"
/>
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"
app:fabSize="normal"
<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:
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:
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:
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;
}
});
}
}
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);} }
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:
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
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:
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.
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.
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:
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:
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
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>
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>
@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:
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:
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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 {
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
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.
<EditText
android:id="@+id/edit_simple" android:layout_height="wrap_content"
android:layout_width="match_parent">
</EditText>
114
Note: In the above figure, #1 is the Return (also known as Enter) key.
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.
android:inputType="phone"
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.
<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:
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()*/
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
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;
Example 2:
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" />
<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;
@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) {
@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) {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
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.
Parameter Description
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.
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;
@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.
If you observe the above result we created a toast notification and shown it on Button click based on our
requirements.
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.
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;
@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.
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.
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.
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.
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;
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.
.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)