MAD Notes - 4 Units
MAD Notes - 4 Units
Android is a software package and linux based operating system for mobile devices such as
tablet computers and smartphones. It was first introduced on Nov 5, 2007. It was originally
developed by Android Inc. and subsequently purchased by Google. Basically, Android is
thought of as a mobile operating system. But it is not limited to mobile-only. It is currently
used in various devices such as mobiles, tablets, televisions, etc.
It is developed by Google and later the OHA (Open Handset Alliance). Java language is mainly
used to write the android code even though other languages can be used.
It is free and open-source software. Java language is mainly used to write the android code
even though other languages can be used.
The goal of android project is to create a successful real-world product that improves the mobile
experience for end users.
Android applications are usually developed in the Java language using the Android Software
Development Kit.
Once developed, Android applications can be packaged easily and sold out either through a
store such as Google Play, SlideME, Opera Mobile Store, Mobango, F-droid and
the Amazon Appstore.
The Open Handset Alliance is an association of 84 companies developing free standards for
mobile devices. Member companies include HTC, Sony, Dell, Intel, Motorola, Qualcomm,
Texas Instruments, Google, Samsung Electronics, LG Electronics, Sprint Corporation, Nvidia.
OHA members are mainly device operators, device manufacturers, software development
firms, semiconductor companies, and commercialization companies. Members share a
commitment to increase the commercial viability of open platform development.
1. Android User
2. Developer
3. Equipment Maker
Collaborate and define with development teams for design and deliver new cool features.
Troubleshoot and fix bugs in new and existing applications for Users.
Evaluate and implement new development tools to work with outside data sources and APIs.
3. Equipment Maker:
Android equipments are available in the market in a huge amount.
Smartwatches: A smartwatch is a handheld, wearable device that closely relates a wristwatch or other time
device. In addition to telling time, many smartwatches are wireless connectivity oriented such as Bluetooth
capable. The traditional watch becomes, in effect, a wireless Bluetooth technology extending the capabilities
of the wearer's smartphone to the watch.
Smart TV: An Android TV box is a small computer that plugs into any TV and gives the user
the ability to stream content, locally and online. Apps can be downloaded from the Google Play
Store, installed, and do most anything a standard computer can do from streaming videos to
writing an email.
Smart Speakers: Smark speakers are booming in the market now, Smark speakers like Google
Home, Alexa, We can control our android device via voice using these smart speakers.
Features of Android
Android is a powerful operating system competing with Apple 4GS and supports great features.
Few of them are listed below −
1
Beautiful UI
Android OS basic screen provides a beautiful and intuitive user interface.
2
Connectivity
GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX.
3
Storage
SQLite, a lightweight relational database, is used for data storage purposes.
4
Media support
H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg
Vorbis, WAV, JPEG, PNG, GIF, and BMP.
5
Messaging
SMS and MMS
6
Web browser
Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine
supporting HTML5 and CSS3.
7
Multi-touch
Android has native support for multi-touch which was initially made available in handsets such
as the HTC Hero.
8
Multi-tasking
User can jump from one task to another and same time various application can run
simultaneously.
9
Resizable widgets
Widgets are resizable, so users can expand them to show more content or shrink them to save
space.
10
Multi-Language
Supports single direction and bi-directional text.
11
GCM
Google Cloud Messaging (GCM) is a service that lets developers send short message data to
their users on Android devices, without needing a proprietary sync solution.
12
Wi-Fi Direct
A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer
connection.
13
Android Beam
A popular NFC-based technology that lets users instantly share, just by touching two NFC-
enabled phones together.
History of Android
The code names of android ranges from A to N currently, such as Aestro, Blender, Cupcake,
Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat,
Lollipop and Marshmallow. Let's understand the android history in a sequence.
What is API level?
API Level is an integer value that uniquely identifies the framework API revision offered by a
version of the Android platform.
10 GINGERBREAD_MR1
Android 2.3.4
Android 2.3.3
9 GINGERBREAD
Android 2.3.2
Android 2.3.1
Android 2.3
you can start your Android application development on either of the following operating
systems −
Microsoft Windows XP or later version.
Mac OS X 10.5.8 or later version with Intel chip.
Linux including GNU C Library 2.7 or later.
Android IDEs
There are so many sophisticated Technologies are available to develop android
applications, the familiar technologies, which are predominantly using tools as follows
Android Studio
Eclipse IDE(Deprecated)
1. Eclipse IDE
2. Android SDK
3. Android Virtual Device
4. Eclipse Plugin
all the required tools to develop Android applications are freely available and can be
downloaded from the Web.
1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications
1) Linux kernel
It is the heart of android architecture that exists at the root of android architecture. Linux
kernel is responsible for device drivers, power management, memory management, device
management and resource access.
2) Native Libraries
On the top of linux kernel, their are Native libraries such as WebKit, OpenGL, FreeType,
SQLite, Media, C runtime library (libc) etc.
The WebKit library is responsible for browser support, SQLite is for database, FreeType for
font support, Media for playing and recording audio and video formats.
3) Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile devices.
It consumes less memory and provides fast performance.
4) Android Framework
On the top of Native libraries and android runtime, there is android framework. Android
framework includes Android API's such as UI (User Interface), telephony, resources,
locations, Content Providers (data) and package managers. It provides a lot of classes and
interfaces for android application development.
5) Applications
On the top of android framework, there are applications. All applications such as home, contact,
settings, games, browsers are using android framework that uses android runtime and libraries.
Android runtime and native libraries are using linux kernal.
Unit 2
Installation and configuration of Android
2.1 Operating System, Java JDK, Android SDK
Operating System
Java JDK
The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment
(JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (javadoc) and other tools needed in Java development
Android SDK
It stands for Android Software Development Kit which is developed by Google for Android
Platform. With the help of Android SDK, we can create android Apps easily.
Android SDK is a collection of libraries and Software Development tools that are essential for
Developing Android Applications. Whenever Google releases a new version or update of
Android Software, a corresponding SDK also releases with it. In the updated or new version of
SDK, some more features are included which are not present in the previous version. Android
SDK consists of some tools which are very essential for the development of Android Application.
These tools provide a smooth flow of the development process from developing and debugging.
Android SDK is compatible with all operating systems such as Windows, Linux, macOS, etc.
The Android SDK is optimized for Android Studio, and hence to effectively reap its benefits,
you will need to install Android Studio. Having the Android SDK managed from within Android
Studio is easier since support for languages like Java, Kotlin, and C++ is handled automatically.
Not only that, but updates to the Android SDK are handled automatically by Android Studio.
The Android SDK (software development kit) is a set of development tools used to develop
applications for Android platform. The Android SDK includes the following:
• Required libraries
• Debugger
• An emulator
• Relevant documentation for the Android application program interfaces (APIs)
• Sample source code
• Tutorials for the Android OS
To install the Android SDK from within Android Studio, first start Android
Studio.
From the Android Studio start page, select Configure > SDK
Manager.
If you already have Android Studio open, the SDK Manager icon is
found on the top right corner, as shown below.
Install the required Android SDK platform packages and developer tools. A
good start is to install:
Click Apply, and Android Studio will install the selected tools and packages.
SDK tools are generally platform-independent and they are required no matter which Android
platform you are currently working on. There are a set of tools that get installed automatically
when you install Android Studio. I’ve tried noting down a few of them:
Tools Description
This tool lets you manage the AVD (Android
Android Virtual Device), projects, and the installed
components of the SDK.
It lets you test your applications without using a
Emulator
physical device.
This tool helps in shrinking, optimizing,
Proguard and obscures your code by removing unused
code.
ddms It lets you debug your Android applications
This is a versatile command-line tool that helps
Android Debug Bridge (Adb) you communicate with an emulator instance or
connected Android-powered device.
All that is required to follow the instructions provided, and the updates will be immediately
downloaded to your environment .
SDK Platform
For each version of Android, there's one SDK Platform available. These are numbered
according to the Android version (e.g. Android 7 Nougat) and an API version (e.g. API Level
24). Before you build an Android app, you must specify an SDK Platform as your build target.
Newer SDK Platform versions have more features for developers, but older devices may not be
compatible with the newer platform versions.
Xamarin was launched in 2011 which is the best free IDE for delivering an enterprise-
quality, cross-platform approach. Xamarin supplies add-ins to Microsoft Visual
Studio that allows developers to build Android, iOS, and Windows apps within the IDE
3. IntelliJ IDEA
It is one of the most popular IDES of Android apps. The open-source software is free to
use. Released under the Eclipse Public License, it holds a large community having plenty
of plugins and configurations. Highly customizable offers full support for Java
programming language and XML.
Notice that only some hardware profiles are indicated to include Play Store.
This indicates that these profiles are fully CTS compliant and may use system
images that include the Play Store app.
The Android emulator provides almost all of the capabilities of a real Android device. You can
perform the following activities:
Often it is faster and easier to test your app with an emulator instead of using a physical
device.
An Android Emulator is a device that simulates an Android device on your system. Suppose
we want to run our android application that we code. One option is that we will run this on our
Android Mobile by Enabling USB Debugging on our mobile. Another option is using Android
Emulator. In Android Emulator the virtual android device is shown on our system on which
we run the Android application that we code.
Thus, it simply means that without needing any physical device Android SDK component
“Android Emulator” provides a virtual device on the System where we run our Application.
The emulator’s come with the configuration for Various android phones, tablets, Wear OS, and
Android TV devices.
In Android Virtual Emulator all functions that are feasible on real Android mobile is works
on virtual Device like:
phone calls, text messages.
stimulate different network speeds.
specify the location of a device
access on google play store and lot’s more.
But there is one disadvantage of this emulator is that. It is very slow when System’s PC has
less RAM. It works fine when a maximum GB of RAM is present on our device.
Launch the Android Emulator without first running an app
To start the emulator:
1. Open the AVD Manager.
2. Double-click an AVD, or click Run
.
The Android Emulator loads.
While the emulator is running, you can run Android Studio projects and choose the
emulator as the target device. You can also drag one or more APKs onto the emulator to
install them, and then run them
2.5 Dalvik Virtual Machine | DVM
As we know the modern JVM is high performance and provides excellent memory management.
But it needs to be optimized for low-powered handheld devices as well.
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.
Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple
class files are converted into one dex file.
Let's see the compiling and packaging process from the source file:
The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file. It is a
platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.
Installation
Follow steps below for complete installation and configuration of Android Studio.
Step 1) Download Android Studio
You can download Android Studio from this link or go
to developer.android.com homepage and search for downloads. Choose appropriate
platform either for windows, mac or linux. Following are the pre requirements for
windows operating system.
Pre-requirements
Click next and select Android SDK checked if you don’t have it already. Better is to leave
the default settings.
Make sure Android virtual device is also checked.
Next step is to accept license and agreement. Click on I Agree
Next step is to set location of installation. Please make sure your disk has minimum
required space before clicking on Next.
For Android Studio installation location must have at least 500MB free space. For Android SDK
installation, selected location must
have at least 3.25GB free space
Next step is to choose the start menu folder, where you want to create shortcut. If you
don’t want to create a shortcut just mark Do not create shortcut
And hit Install button.
It will start installation. Once it’s done following window will appear.
This informs you installation has completed. Click Finish. Make sure Start Android
Studio is checked. Following splash screen of Android Studio will appear
Step 3) Configure Android Studio
When you run it for the first time it will ask for Android Studio settings.
If you don’t have any previous settings click on the second option (I don’t have a
previous version of Studio or I don’t want to import my settings).
Select a theme and click next
At the very first run it needs to download some necessary components, wait till it
completes.
And it’s all done
1. All resource files are combined together by AAP[Android Asset Packing Tool].
Resource files are like audio video images other asset related files. 2.Java files
converted into .class files by JVM.So, the out of the jvm will be .class files, that
are heavy weight to put into android. So, that one more level of process will be
taken place.
2. So, the .Class files are entered as input to DX tool. Basically, this is a tool which
will convert .class files to .dex files. That mean Dalvik executable file. Those files
are eligible to execute on DVM (Dalvik Virtual Machine)
3. After getting .dex files, packed them APK builder. Which is basically, Application
Packaging. So, this packed files kept into devices and that will be executed by
DVM.
Directory Structure
Before you run your app, you should be aware of a few directories and files in the
Android project −
Java
1 This contains the .java source files for your project. By default, it
includes an MainActivity.java source file having an activity class that
runs when your app is launched using the app icon.
res/drawable-hdpi
2
This is a directory for drawable objects that are designed for high-
density screens.
res/layout
3
This is a directory for files that define your app's user interface.
res/values
4 This is a directory for other various XML files that contain a collection
of resources, such as strings and colours definitions.
AndroidManifest.xml
5 This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.
Build.gradle
Following section will give a brief overview of the important application files.
package com.example.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
For example, a default manifest file will look like as following file −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here <application>...</application> tags enclosed the components related to the
application. Attribute android:icon will point to the application icon available
under res/drawable-hdpi. The application uses the image named ic_launcher.png
located in the drawable folders
The <activity> tag is used to specify an activity and android:name attribute specifies
the fully qualified class name of the Activity subclass and the android:label attributes
specifies a string to use as the label for the activity. You can specify multiple activities
using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate that this
activity serves as the entry point for the application. The category for the intent-filter
is named android.intent.category.LAUNCHER to indicate that the application can be
launched from the device's launcher icon.
The @string refers to the strings.xml file explained below.
Hence, @string/app_name refers to the app_name string defined in the strings.xml
file, which is "HelloWorld". Similar way, other strings get populated in the application.
Following is the list of tags which you will use in your manifest file to specify different
Android application components −
<activity>elements for activities
<service> elements for services
<receiver> elements for broadcast receivers
<provider> elements for content providers
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
This is an example of simple RelativeLayout which we will study in a separate chapter.
The TextView is an Android control used to build the GUI and it have various attributes
like android:layout_width, android:layout_height etc which are being used to set its
width and height etc.. The @string refers to the strings.xml file located in the
res/values folder. Hence, @string/hello_world refers to the hello string defined in the
strings.xml file, which is "Hello World!".
Activity
An activity is a class that represents a single screen. It is like a Frame in AWT.
Layout
It is a type of resource which gives definition on what is drawn on the screen or how
elements are placed on the device’s screen and stored as XML files in the /res/layout
resource directory for the application. It can also be a type of View class to organize
other controls.
Fundamental UI Design
Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.
Services
2
They handle background processing associated with an application.
Broadcast Receivers
3
They handle communication between Android OS and applications.
Content Providers
4
They handle data and database management issues.
Activities
An activity represents a single screen with a user interface,in-short Activity performs
actions on the screen. For example, an email application might have one activity that
shows a list of new emails, another activity to compose an email, and another activity
for reading emails. If an application has more than one activity, then one of them
should be marked as the activity that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows −
public class MainActivity extends Activity {
}
Services
A service is a component that runs in the background to perform long-running
operations. For example, a service might play music in the background while the user
is in a different application, or it might fetch data over the network without blocking
user interaction with an activity.
A service is implemented as a subclass of Service class as follows −
public class MyService extends Service {
}
Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications
or from the system. For example, applications can also initiate broadcasts to let other
applications know that some data has been downloaded to the device and is available
for them to use, so this is broadcast receiver who will intercept this communication
and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and
each message is broadcaster as an Intent object.
public class MyReceiver extends BroadcastReceiver {
public void onReceive(context,intent){}
}
Content Providers
A content provider component supplies data from one application to others on request.
Such requests are handled by the methods of the ContentResolver class. The data
may be stored in the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform
transactions.
public class MyContentProvider extends ContentProvider {
public void onCreate(){}
}
We will go through these tags in detail while covering application components in
individual chapters.
Additional Components
There are additional components which will be used in the construction of above
mentioned entities, their logic, and wiring between them. These components are −
Fragments
1
Represents a portion of user interface in an Activity.
Views
2
UI elements that are drawn on-screen including buttons, lists forms etc.
Layouts
3
View hierarchies that control screen format and appearance of the views.
Intents
4
Messages wiring components together.
Resources
5
External elements, such as strings, constants and drawable pictures.
Manifest
6
Configuration file for the application.
https://www.tutorialspoint.com/android/android_user_interface_la
youts.htm
1 Linear Layout
LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
2 Relative Layout
RelativeLayout is a view group that displays child views in relative positions.
3 Table Layout
TableLayout is a view that groups views into rows and columns.
4 Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.
5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a single view.
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout.
There are few common attributes among all the layouts and their are other attributes
which are specific to that layout. Following are common attributes and will be applied
to all the layouts:
1
android:id
This is the ID which uniquely identifies the view.
2
android:layout_width
This is the width of the layout.
3
android:layout_height
This is the height of the layout
4
android:layout_marginTop
This is the extra space on the top side of the layout.
5
android:layout_marginBottom
This is the extra space on the bottom side of the layout.
6
android:layout_marginLeft
This is the extra space on the left side of the layout.
7
android:layout_marginRight
This is the extra space on the right side of the layout.
8
android:layout_gravity
This specifies how child Views are positioned.
9
android:layout_weight
This specifies how much of the extra space in the layout should be allocated to the
View.
10
android:layout_x
This specifies the x-coordinate of the layout.
11
android:layout_y
This specifies the y-coordinate of the layout.
12
android:layout_width
This is the width of the layout.
13
android:paddingLeft
This is the left padding filled for the layout.
14
android:paddingRight
This is the right padding filled for the layout.
15
android:paddingTop
This is the top padding filled for the layout.
16
android:paddingBottom
This is the bottom padding filled for the layout.
Here width and height are the dimension of the layout/view which can be specified in
terms of dp (Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points
which is 1/72 of an inch), px( Pixels), mm ( Millimeters) and finally in (inches).
What is the Difference Between “px”, “dip”,
“dp” and “sp” in Android?
An XML-defined dimension value. A dimension is denoted by a number followed by a
unit of measurement. For instance, 25px, 5in, 10dp and 10sp. When you use sp/dp,
your Android applications will be compatible with a wide range of screen densities
and resolutions.
PX: is an abbreviation for Pixels, which specifies the actual pixels on the screen.
SP: is an abbreviation for Scale independent pixels. It is the same as the dp unit,
but it is additionally scaled according to the user’s font size selection.
DP: A virtual pixel unit used to communicate layout dimensions or location in a
density-independent manner while creating UI layout. The density-independent
pixel corresponds to one physical pixel on a 160 dpi screen, which is the
system’s baseline density for a “medium” density screen. At runtime, the system
handles any scaling of the dp units that is required based on the actual density of
the screen in use in a transparent manner.
You can specify width and height with exact measurements but more often, you will
use one of these constants to set the width or height −
android:layout_width=wrap_content tells your view to size itself to the
dimensions required by its content.
android:layout_width=fill_parent tells your view to become as big as its
parent view.
o Padding provides the space between the border and the content of an element.
o Margin provides the space between the border and outer elements.
So, when we require the space between the elements, then it is better to use margin,
and when we need the space between the inner element and the parent box, then go
for padding.
We can see the following image to clear the difference between the margin and
padding. In this image, the margin indicates the area outside the border and the
padding indicates the area inside the border.
Margin
Margin is a way for a view to enforce some distance from others views. By specifying
margin for a view, we say that keep this much distance from this view. Android has 5
kinds of margins.
<TextView
android:background="@color/highlighted_text_material_dark"
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:layout_margin="40dp"
android:text="Text 1"
android:textColor="@color/accent_material_dark"/>
<LinearLayout
android:orientation="vertical"
android:background="@color/highlighted_text_material_dark"
android:id="@+id/layout1"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@color/accent_material_dark"/>
</LinearLayout>
In the above example there is a LinearLayout(Parent of all views) which does not
have any margin specified. But the textView has a margin of 20dp, and according to
our earlier definition the text view is saying that keep 20dp distance from me in all the
sides. That is why the textView has the 20dp space in all the directions. Then there is
LinearLayout sibling of textView which says in left, right and bottom keep 10dp
distance from me and hence there is space in all 3 sides.
Padding
Padding is a way to push the contents away from view’s inner boundary. When we
specify the padding of a view, we say the content to keep this much distance from
your inner boundary(left, right, top or bottom). Like margin, padding is also of 5
types.
Example
<TextView
android:background="@color/highlighted_text_material_dark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:paddingLeft="40dp"
android:text="paddingLeft"
android:layout_margin="10dp"
android:textColor="@color/accent_material_dark"/>
<TextView
android:background="@color/highlighted_text_material_dark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:paddingRight="40dp"
android:text="paddingRight"
android:layout_margin="10dp"
android:textColor="@color/accent_material_dark"/>
<TextView
android:background="@color/highlighted_text_material_dark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:paddingTop="20dp"
android:text="paddingTop"
android:layout_margin="10dp"
android:textColor="@color/accent_material_dark"/>
<TextView
android:background="@color/highlighted_text_material_dark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:paddingBottom="20dp"
android:text="paddingBottom"
android:layout_margin="10dp"
android:textColor="@color/accent_material_dark"/>
<TextView
android:background="@color/high
lighted_text_material_dark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:padding="20dp"
android:text="padding"
android:layout_margin="10dp"
android:textColor="@color/accent_material_dark"/>
</LinearLayout>
Weight and Weight_sum in Android
<EditText
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Type Your Text Here" />
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Text1" />
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Text1" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
android:background="@color/black">
<Button
android:id="@+id/b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />
<Button
android:id="@+id/b2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button2"
app:backgroundTint="#4CAF50" />
<Button
android:id="@+id/b3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button3"
app:backgroundTint="#B51ACF" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/button"
android:background="#358a32" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:id="@+id/button2"
android:background="#0058b6" />
</LinearLayout>
2. Horizontal:
In this all the child are arranged horizontally in a line one after the other. In below code
snippets we have specified orientation “horizontal” so the childs/views of this layout
are displayed horizontally.<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 -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:id="@+id/button2"
android:background="#0058b6" />
</LinearLayout>
</LinearLayout>
2. gravity: The gravity attribute is an optional attribute which is used to control the
alignment of the layout like left, right, center, top, bottom etc.
Example: We have set gravity right for linear layout. So the buttons gets align from
right side in Horizontal orientation.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="horizontal">
<!--Button Child View Here--->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:id="@+id/button2"
android:background="#0e7d0d" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/button"
android:background="#761212" />
</LinearLayout>
3. layout_weight: The layout weight attribute specify each child control’s relative
importance within the parent linear layout.
Example: weight property for button in linear layout. In the below example one button
is of weight 2 and other is of weight 1.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<!--Add Child View Here--->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Weight 2"
android:background="#761212"
android:layout_margin="5dp"
android:id="@+id/button"
android:layout_weight="2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#761212"
android:layout_margin="5dp"
android:layout_weight="1"
android:text="Weight 1" />
</LinearLayout>
In the layout image you can notice Button with weight 2 gets more size related the
other.
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: In the same above example of weight, we can define weightSum value 3.
<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">
<!--Add Child View Here--->
</LinearLayout>
An Absolute Layout lets you specify exact locations (x/y coordinates) of its children.
Absolute layouts are less flexible and harder to maintain than other types of layouts
without absolute positioning.
Absolute Layout
AbsoluteLayout Attributes
Following are the important attributes specific to AbsoluteLayout −
android:id
1 This is the ID which uniquely identifies the layout.
android:layout_x
2 This specifies the x-coordinate of the view.
android:layout_y
3 This specifies the y-coordinate of the view.
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_x="110px"
android:layout_y="110px"
android:text="User Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:layout_x="250px"
android:layout_y="80px"
android:width="100px"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<TextView
android:layout_x="110px"
android:layout_y="200px"
android:text="Password"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:layout_x="250px"
android:layout_y="150px"
android:width="100px"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
android:layout_x="300px"
android:layout_y="300px"/>
</AbsoluteLayout>
2.Frame Layout
Frame Layout is designed to block out an area on the screen to display a single item.
Generally, FrameLayout should be used to hold a single child view, because it can be
difficult to organize child views in a way that's scalable to different screen sizes without
the children overlapping each other.
You can, however, add multiple children to a FrameLayout and control their position
within the FrameLayout by assigning gravity to each child, using the
android:layout_gravity attribute.
Following will be the content of res/layout/activity_main.xml file −
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView
android:text="Frame Demo"
android:textSize="30px"
android:textStyle="bold"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
For building a row in a table we will use the <TableRow> element. Table row objects
are the child views of a table layout.
...
</TableLayout>
...
</TableLayout>
3. shrinkColumns: Shrink column attribute is used to shrink or reduce the width of the
column‘s. We can specify either a single column or a comma delimited list of column
numbers for this attribute. The content in the specified columns word-wraps to reduce
their width.
If the value is 0 then the first column’s width shrinks or reduces by word wrapping its
content.
If the value is 0,1 then both first and second columns are shrinks or reduced by word
wrapping its content.
If the value is ‘*’ then the content of all columns is word wrapped to shrink their
widths.
Below is the example code of shrink column attribute of table layout with explanation
included in which we shrink the first column of layout.
4.View - android:collapseColumns
...
</TableLayout>
...
</TableLayout>
5.View - android:layout_column
<TableRow
android:paddingTop="10px"
android:gravity="center">
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_span="2"
android:text="LOGIN"
android:textColor="#890000"
android:textSize="15sp"
android:textStyle="bold" />
</TableRow>
<TextView
android:layout_width="wrap_content"
android:text="Username :"
android:textSize="20sp"
android:textColor="#000000"
android:layout_marginLeft="20dip">
</TextView>
<EditText
android:id="@+id/screenName"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1" >
</EditText>
</TableRow>
<TextView
android:text="Password :"
android:layout_width="wrap_content"
android:textSize="20sp"
android:textColor="#000000"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip">
</TextView>
<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_weight="1" >
</EditText>
</TableRow>
<TableRow
android:gravity="center"
android:layout_marginTop="20dip" >
<Button
android:text="Submit"
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/save"
android:layout_span="2" >
</Button>
</TableRow>
</TableLayout>
Attribute Description
layout_alignParentTop If it specified “true”, the top edge of view will match the top edge of
the parent.
layout_alignParentBottom If it specified “true”, the bottom edge of view will match the bottom
edge of parent.
layout_alignParentLeft If it specified “true”, the left edge of view will match the left edge of
parent.
layout_alignParentRight If it specified “true”, the right edge of view will match the right edge
of the parent.
layout_centerInParent If it specified “true”, the view will be aligned to the centre of parent.
layout_centerVertical If it specified “true”, the view will be vertically centre aligned within
its parent.
layout_above It accepts another sibling view id and places the view above the
specified view id.
layout_below It accepts another sibling view id and places the view below the
specified view id.
layout_toLeftOf It accepts another sibling view id and places the view left of the
specified view id.
layout_toRightOf It accepts another sibling view id and places the view right of the
specified view id.
layout_toStartOf It accepts another sibling view id and places the view to start of the
specified view id.
layout_toEndOf It accepts another sibling view id and places the view to the end of
the specified view id.
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"
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>
Output of Android RelativeLayout Example
Unit 4
Designing User Interface with View
Android View
View is a basic building block of UI (User Interface) in android. A view is a small rectangular box
that responds to user inputs. Eg: EditText, Button, CheckBox, etc. The View class is the base
class or we can say that it is the superclass for all the GUI components in android
ViewGroup
The ViewGroup class is a subclass of the View class. And also it will act as a base class for
layouts and layouts parameters. The ViewGroup will provide an invisible container to hold other
Views or ViewGroups and to define the layout properties. For example, Linear Layout is the
ViewGroup that contains UI controls like Button, TextView, etc., and other layouts also.
Android TextView
In android, TextView is a user interface control that is used to set and display the text to the user
based on our requirements. The TextView control will act as like label control and it won’t allow
Attribute Description
android:autoLink It will automatically found and convert URLs and email addresses
as clickable links.
android: ems It is used to make the textview be exactly this many ems wide.
android:gravity It is used to specify how to align the text by the view's x and y-axis.
android:maxWidth It is used to make the TextView be at most this many pixels wide.
android:minWidth It is used to make the TextView be at least this many pixels wide.
android:inputType It is used to specify the type of text being placed in text fields.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
Output
Android Edit Text
EditText is a Widget of user interface (UI) used to retrieve and modify text data from a user in an
Android app
android:inputType It is used to mention what type of value should pass in EditText, like
plain text, email, password, etc
android:gravity gravity is used to align the text like left, right, center, top
android:textStyle It is used to set the text style like bold, italic, bold italic, etc.
android:textColor It is used to set the color of the text
android:drawablePaddin It is used to set the drawable to be drawn from the set padding of
g View
Android Button
In android, Button is a user interface control that is used to perform an action whenever
the user clicks or tap on it.
Android Button represents a push-button. The android.widget.Button is subclass of
TextView class and CompoundButton is the subclass of Button class.
Generally, Buttons in android will contain a text or an icon or both and perform an action
when the user touches it.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
<EditText
android:id="@+id/firstNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Number"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/secondNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Add" />
</LinearLayout>
MainActivity.java
package com.tutlane.buttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(firstNum.getText().toString().isEmpty() ||
secNum.getText().toString().isEmpty())
else {
});
Android ImageButton
In android, Image Button is a user interface control that is used to display a button with an image
and to perform an action when a user clicks or taps on it.
By default, the ImageButton looks same as normal button and it performs an action when a user
clicks or touches it, but the only difference is we will add a custom image to the button instead of
text.
In android, we have different types of buttons available to use based on our requirements, those are
Button, ImageButton, ToggleButton, and RadioButton.
Following is the sample way to define ImageButton control in XML layout file in android application.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/add_icon" />
</LinearLayout>
If you observe above code snippet, here we defined ImageButton control and we are showing the
image from drawable folder using android:src attribute in xml layout file.
Following are some of the commonly used attributes related to ImageButton control in android
applications.
Attribute Description
android:padding It is used to set the padding from left, right, top and bottom of
the image button.
android:baseline It is used to set the offset of the baseline within the view.
The ToggleButton is useful for the users to change the settings between two states either ON or
OFF.
It is beneficial if user have to change the setting between two states. It can be used to On/Off
Sound, Wifi, Bluetooth etc.
We can add a ToggleButton to our application layout by using the ToggleButton object.
By default, the android ToggleButton will be in OFF (Unchecked) state. We can change the default
state of ToggleButton by using android:checked attribute.
In case, if we want to change the state of ToggleButton to ON (Checked), then we need to set
android:checked = “true” in our XML layout file.
The following are some of the commonly used attributes related to ToggleButton control in android
applications.
Attribute Description
android:gravity It is used to specify how to align the text like left, right,
center, top, etc.
android:textOn It is used to set the text when the toggle button is in the ON
/ Checked state.
android:textOff It is used to set the text when the toggle button is in the
OFF / Unchecked state.
android:padding It is used to set the padding from left, right, top and bottom.
This is how we can use ToggleButton control in android applications to switch the settings between
two states either ON or OFF based on our requirements.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ToggleButton
android:id="@+id/toggle1"
android:layout_width="wrap_content"
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>
If you observe above code we defined a two ToggleButton controls and one Button control in
RelativeLayout to get the state of ToggleButton controls when we click on Button control in XML layout
file.
Once we are done with the creation of layout with required control, 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.togglebuttonexample path and write the code like as
shown below.
MainActivity.java
package com.tutlane.togglebuttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
});
Important Note: RadioGroup is a widget used in Android for the grouping of radio
buttons and provide the feature of selecting only one radio button from the set.
When a user try to select any other radio button within same radio group the
previously selected radio button will be automatically unchecked.
activity_main.xml
MainActivity.java
package com.tutlane.radiobuttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the
user, activate/deactivate the specific action etc.
Attributes of CheckBox:
1.id: id is an attribute used to uniquely identify a check box. Below we set the id of a image
button.
<CheckBox
android:id="@+id/simpleCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Simple CheckBox"/>
2. checked: checked is an attribute of check box used to set the current state of a check
box. The value should be true or false where true shows the checked state and false shows
unchecked state of a check box. The default value of checked attribute is false. We can
also set the current state programmatically.
Below is an example code in which we set true value for checked attribute that sets the
current state to checked.
<CheckBox
android:id="@+id/simpleCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Simple CheckBox"
android:checked="true"/> <!--set the current state of the check box-->
3. gravity: The gravity attribute is an optional attribute which is used to control the
alignment of the text in CheckBox like left, right, center, top, bottom, center_vertical,
center_horizontal etc.
Below we set the right and center_vertical gravity for the text of a check box.
<CheckBox
android:id="@+id/simpleCheckBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Simple CheckBox"
android:checked="true"
4. text: text attribute is used to set the text in a check box. We can set the text in xml as
well as in the java class.
Below is the example code with explanation included in which we set the text “Text
Attribute Of Check Box” for a check box.
<CheckBox
android:id="@+id/simpleCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
5. textColor: textColor attribute is used to set the text color of a check box. Color value is
in form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.
6. textSize: textSize attribute is used to set the size of text of a check box. We can set
the text size in sp(scale independent pixel) or dp(density pixel).
7. textStyle: textStyle attribute is used to set the text style of the text of a check box.
The possible text styles are bold, italic and normal. If we need to use two or more styles
for a text view then “|” operator is used for that.\
8. background: background attribute is used to set the background of a check box. We
can set a color or a drawable in the background of a check box.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/chkJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onCheckboxClicked"/>
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Get Details" />
</LinearLayout>
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.Toast;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (CheckBox)findViewById(R.id.chkAndroid);
angular = (CheckBox)findViewById(R.id.chkAngular);
java = (CheckBox)findViewById(R.id.chkJava);
python = (CheckBox)findViewById(R.id.chkPython);
Button btn = (Button)findViewById(R.id.getBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String result = "Selected Courses";
if(android.isChecked()){
result += "\nAndroid";
}
if(angular.isChecked()){
result += "\nAngularJS";
}
if(java.isChecked()){
result += "\nJava";
}
if(python.isChecked()){
result += "\nPython";
}
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_SHORT).show();
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.chkAndroid:
str = checked?"Android Selected":"Android Deselected";
break;
case R.id.chkAngular:
str = checked?"AngularJS Selected":"AngularJS Deselected";
break;
case R.id.chkJava:
str = checked?"Java Selected":"Java Deselected";
break;
case R.id.chkPython:
str = checked?"Python Selected":"Python Deselected";
break;
}
Toast.makeText(getApplicationContext(), str,
Toast.LENGTH_SHORT).show();
}
}
In Android, ProgressBar is used to display the status of work being done like analyzing
status of work or downloading a file etc. In Android, by default a progress bar will be
displayed as a spinning wheel but If we want it to be displayed as a horizontal bar then
we need to use style attribute as horizontal. It mainly use the
“android.widget.ProgressBar” class.
ProgressBar code:
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>
Now let’s discuss important attributes that helps us to configure a Progress bar in xml file
(layout).
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>
2. max: max is an attribute used in android to define maximum value of the progress can
take. It must be an integer value like 100, 200 etc.
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
Below we set the 100 max value and then set 50 default progress.
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
Below we set a custom gradient drawable for the progress mode of a progress bar. Before
you try below code make sure to download a progress icon from the web and add in your
drawable folder.
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="60"
android:layout_marginTop="100dp"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
Step 2: Create a new drawable resource xml in drawable folder and name it
custom_progress. Here add the below code which creates gradient effect in progressbar.
<item>
<shape>
<gradient
android:endColor="#fff"
android:startColor="#1f1"
android:useLevel="true" />
</shape>
</item>
</layer-list>
Below we set the black color for the background of a Progress bar.
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
android:background="#000"
android:padding="20dp" style="@style/Widget.AppCompat.ProgressBar.Horizontal"
7. padding: padding attribute is used to set the padding from left, right, top or bottom of
ProgressBar.
● paddingRight: set the padding from the right side of the Progress bar.
● paddingLeft: set the padding from the left side of the Progress bar.
● paddingTop: set the padding from the top side of the Progress bar.
● paddingBottom: set the padding from the bottom side of the Progress bar.
● Padding: set the padding from the all side’s of the Progress bar.
Below we set the 20dp padding from all the side’s of the Progress bar.
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
android:background="#000"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:padding="20dp"/><!--// 20dp padding from all the sides of the progress bar-->
1. The first ProgressBar is put in Determinate mode. It displays a process which the percentage of
complete work is indicated.
2. The second ProgressBar is put in Indeterminate mode. It will show a progress for which you cannot
know the percentage of completed work.
**Output of Progress Bar
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ProgressBar
android:id="@+id/pBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:minHeight="50dp"
android:minWidth="200dp"
android:max="100"
android:indeterminate="false"
android:progress="0" />
<TextView
android:id="@+id/tView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/pBar"
android:layout_below="@+id/pBar" />
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Start Progress"
android:layout_below="@+id/tView"/>
</RelativeLayout>
MainActivity.java
package com.tutlane.progressbarexample;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
private int i = 0;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn.setOnClickListener(new View.OnClickListener() {
@Override
i = pgsBar.getProgress();
i += 1;
// Update the progress bar and display the current value in text view
hdlr.post(new Runnable() {
public void run() {
pgsBar.setProgress(i);
txtView.setText(i+"/"+pgsBar.getMax());
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}).start();
});
}
Android Adapter
In android, Adapter will act as an intermediate between the data sources and adapter views such as
ListView, Gridview to fill the data into adapter views. The adapter will hold the data and iterates
through an items in data set and generate the views for each item in the list.
Generally, in android we have a different types of adapters available to fetch the data from different
data sources to fill the data into adapter views, those are
In android, ListView is a ViewGroup that is used to display the list of scrollable of items in multiple
rows and the list items are automatically inserted to the list using an adapter.
Generally, the adapter pulls data from sources such as an array or database and converts each item
into a result view and that’s placed into the list.
List of scrollable items can be displayed in Android using ListView. It helps you to displaying the data
in the form of a scrollable list. Users can then select any list item by clicking on it. ListView is default
scrollable so we do not need to use scroll View or anything else with ListView.
ListView is widely used in android applications. A very common example of ListView is your phone
contact book, where you have a list of your contacts displayed in a ListView and if you click on it then
user information is displayed.
Attributes of ListView:
3. dividerHeight: This specify the height of the divider between list items. This could
be in dp(density pixel),sp(scale independent pixel) or px(pixel).
In above example of divider we also set the divider height 1dp between the list items.
The height should be in dp,sp or px.
4. listSelector: listSelector property is used to set the selector of the listView. It is
generally orange or Sky blue color mostly but you can also define your custom color or
an image as a list selector as per your design.
Below is listSelector example code with explanation includes, where list selector color
is green, when you select any list item then that item’s background color is green .
<!-- List Selector Code in ListView -->
<ListView
android:id="@+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#f00"
android:dividerHeight="1dp"
android:listSelector="#0f0"/> <!--list selector in green color-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/userlist"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Once we are done with creation of layout, now we will bind data to our ListView using
ArrayAdapter, for that open main activity file MainActivity.java from
\java\com.tutlane.listview path and write the code like as shown below.
MainActivity.java
package com.tutlane.listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
private String[] users = { "Suresh Dasari", "Rohini Alavala", "Trishika Dasari", "Praveen
Alavala", "Madav Sai", "Hamsika Yemineni"};
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView.setAdapter(aAdapter);
GridView In Android
A GridView is a type of AdapterView that displays items in a two-dimensional
scrolling grid. Items are inserted into this grid layout from a database or from an
array. The adapter is used for displaying this data, setAdapter() method is used
to join the adapter with GridView. The main function of the adapter in GridView is
to fetch data from a database or array and insert each piece of data in an
appropriate item that will be displayed in GridView.
GridView is widely used in android applications. An example of GridView is your default
Gallery, where you have number of images displayed using grid.
Following is the pictorial representation of GridView in android applications.
Attributes of GridView:
Below is the id attribute’s example code with explanation included in which we don’t
specify the number of columns in a row that’s why the GridView behaves like a ListView.
Below is the numColumns example code where we define 4 columns to show in the
screen.
<!-- numColumns example code -->
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="4"/> <!-- numColumns set to 4-->
Important Note: In the below code we also used listSelector property which define color
for selected item. Also to see the output of columnWidth using listSelector we need to
use Adapter which is our next topic. The below code is not sufficient to show you the
output.
<!--columnWidth in Grid view code-->
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:columnWidth="80dp"
android:listSelector="#0f0"/><!--define green color for selected item-->
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="110dp"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />
import androidx.appcompat.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.GridView;
import android.os.Bundle;
ImageView In Android
In Android, ImageView class is used to display an image file in application. Image file is
easy to use but hard to master in Android, because of the various screen sizes in Android
devices. An android is enriched with some of the best UI design widgets that allows us to
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion" />
Attributes of ImageView:
Now let’s we discuss some important attributes that helps us to configure a ImageView
1. id: id is an attribute used to uniquely identify a image view in android. Below is the
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
2. src: src is an attribute used to set a source file or you can say image in your imageview
in drawable folder.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
Below is the example code in which we set the black color in the background and an image
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
4. padding: padding attribute is used to set the padding from left, right, top or bottom of
the Imageview.
● paddingRight: set the padding from the right side of the image view.
● paddingLeft: set the padding from the left side of the image view.
● paddingTop: set the padding from the top side of the image view.
● paddingBottom: set the padding from the bottom side of the image view.
● padding: set the padding from the all side’s of the image view.
Below is the example code of padding attribute in which we set the 30dp padding from
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000"
android:src="@drawable/lion"
5. scaleType: scaleType is an attribute used to control how the image should be re-sized
or moved to match the size of this image view. The value for scale type attribute can be
fit_xy.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
Example of ImageView:
Step 2: Download two images lion and monkey from the web. Now save those images in
the drawable folder of your project.
Step 3: Now open res -> layout -> activity_main.xml (or) main.xml and add following
code:
<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">
<ImageView
android:id="@+id/simpleImageViewLion"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="@drawable/lion" />
<ImageView
android:id="@+id/simpleImageViewMonkey"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="@+id/simpleImageViewLion"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:src="@drawable/monkey" />
</RelativeLayout>
ScrollView And Horizontal ScrollView in android
In android, ScrollView is a kind of layout that is useful to add vertical or horizontal scroll bars to the
content which is larger than the actual size of layouts such as linearlayout, relativelayout, framelayout,
etc.
Generally, the android ScrollView is useful when we have content that doesn’t fit our android app
layout screen. The ScrollView will enable a scroll to the content which is exceeding the screen layout
and allow users to see the complete content by scrolling.
The android ScrollView can hold only one direct child. In case, if we want to add multiple views within
the scroll view, then we need to include them in another standard layout like linearlayout,
relativelayout, framelayout, etc.
To enable scrolling for our android applications, ScrollView is the best option but we should not use
ScrollView along with ListView or Gridview because they both will take care of their own vertical
scrolling.
In android, ScrollView supports only vertical scrolling. In case, if we want to implement horizontal
scrolling, then we need to use a HorizontalScrollView component.
Following is the example of enabling vertical scrolling to the content which is larger than the layout
screen using an android ScrollView object.
activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="false">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/loginscrn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="ScrollView"
android:textSize="25dp"
android:textStyle="bold"
android:layout_gravity="center"/>
<TextView android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Welcome to Tutlane"
android:layout_gravity="center"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
</LinearLayout>
</ScrollView>
If you observe above code, we used a ScrollView to enable the scrolling for linearlayout whenever
the content exceeds layout screen.
When we run the above example in android emulator we will get a result as shown below.
As we discussed, ScrollView can provide only vertical scrolling for the layout. In case, if we want to
enable horizontal scrolling, then we need to use HorizontalScrollView in our application.
We will see how to enable horizontal scrolling for the content which is exceeding the layout screen in
the android application.
Now open activity_main.xml file in your android application and write the code like as shown below.
When we run the above example in the android emulator we will get a result like as shown below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="wrap_content"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
</LinearLayout>
</HorizontalScrollView>
If you observe above code, we used a HorizontalScrollView to enable horizontal scrolling for
linearlayout whenever the content exceeds layout screen.
Home Work-
Android Custom Toast
In android, Toast is a small popup notification that is used to display information about the operation
which we performed in our app. The Toast will show the message for a small period of time and it
will disappear automatically after a timeout.
Generally, the size of Toast will be adjusted based on the space required for the message and it will
be displayed on the top of the main content of activity for a short period of time.
To know more about creation of Toast in android applications, check this Android Toast with
Examples.
Generally, the Toast notification in android will be displayed with simple text like as shown in above
image. In android, we can customize the layout of our toast notification to change the appearance of
based on requirements like include images in toast notification or change the background color of
toast notification, etc.
activity_main.xml
<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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#80CC28">
<ImageView android:src="@drawable/ic_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<TextView android:id="@+id/txtvw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:textColor="#FFF"
android:textStyle="bold"
android:textSize="15dp" />
</LinearLayout>
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.tutlane.toastexample path and write the code like as shown
below.
MainActivity.java
package com.tutlane.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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
@Override
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 100);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
});
The LayoutInflater class is used to instantiate the contents of layout XML files into their
corresponding View objects.
In other words, it takes an XML file as input and builds the View objects from it.
Android DatePicker
In android, DatePicker is a control that will allow users to select the date by a day, month and year
in our application user interface.
If we use DatePicker in our application, it will ensure that the users will select a valid date.
Generally, in android DatePicker available in two modes, one is to show the complete calendar and
another one is to show the dates in spinner view.
We can define android DatePicker to show only a calendar view by using DatePicker
android:datePickerMode attribute.
Following is the example of showing the DatePicker in Calendar mode.
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="calendar"/>
The above code snippet will return the DatePicker in android like as shown below
If you observe the above result we got the DatePicker in calendar mode to select a date based on
our requirements.
If we want to show the DatePicker in spinner format like showing day, month and year separately to
select the date, then by using DatePicker android:datePickerMode attribute we can achieve this.
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>
The above code snippet will return the DatePicker in android like as shown below
If you observe the above result we got the DatePicker in both Spinner and Calendar modes to select
the date.
To get only spinner mode date selection, then we need to set android:calendarViewShown="false"
attribute in DatePicker control like as shown below.
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:calendarViewShown="false"/>
The above code will return the DatePicker like as shown below
If you observe the above result we got the DatePicker in spinner mode to select the date separately
by day, month and year.
This is how we can use DatePicker in different modes based on our requirements in android
applications.
The following are some of the commonly used attributes related to DatePicker control in android
applications.
Attribute Description
android:background It is used to set the background color for the date picker.
android:padding It is used to set the padding for left, right, top or bottom of
the date picker.
Android DatePicker Example
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/datePicker1"
android:layout_marginLeft="100dp"
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginLeft="100dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="18dp"/>
</RelativeLayout>
MainActivity.java
package com.tutlane.datepickerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
DatePicker picker;
Button btnGet;
TextView tvw;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker1);
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
});
When we run the above example using an android virtual device (AVD) we will get a result like as
shown below.
Android TimePicker
In android, TimePicker is a widget for selecting the time of day, in either 24-hour or AM/PM mode.
If we use TimePicker in our application, it will ensure that the users will select a valid time for the
day.
<TimePicker android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="clock" />
The above code will return the TimePicker like as shown below.
If you observe the above result we got the TimePicker in clock mode to select a time in Hours and
Minutes based on our requirements.
<TimePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"/>
The above code will return the TimePicker like as shown below
If you observe the above result we got the TimePicker in spinner mode to select the time in Hours
and Minutes.
We can change the TimePicker in spinner mode to AM / PM format instead of 24 Hours format by
using the setIs24HourView(true) method in Activity file like as shown below.
TimePicker picker=(TimePicker)findViewById(R.id.timePicker1);
picker.setIs24HourView(true);
The above code will return the TimePicker like as shown below
If you observe the above result we got the TimePicker with AM / PM format in spinner mode to
select the time separately by hours, minutes and AM/PM.
This is how we can use TimePicker in different modes based on our requirements in android
applications.
Android TimePicker Control Attributes
The following are some of the commonly used attributes related to TimePicker control in android
applications.
Attribute Description
android:background It is used to set the background color for the date picker.
android:padding It is used to set the padding for left, right, top or bottom of
the date picker.
Create a new android application using android studio and give names as TimePickerExample. In
case if you are not aware of creating an app in android studio check this article Android Hello World
App.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_paren
t">
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/timePicker1"
android:layout_marginTop="10dp"
android:layout_marginLeft="160dp"
android:text="Get Date" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginLeft="120dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="18dp"/>
</RelativeLayout>
If you observe above code we created a one TimePicker control, one TextView control and
one Button control in XML Layout file.
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.tutlane.timepickerexample path and write the
code like as shown below.
MainActivity.java
package com.tutlane.timepickerexample;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
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.
Now we will see another example of showing the TimePicker control on the EditText click event and
get the selected time value in the android application.
Android AutoCompleteTextView
In android, AutoCompleteTextView is an editable text view which is used to show the list of
suggestions based on the user typing text. The list of suggestions will be shown as a dropdown
menu from which the user can choose an item to replace the content of the textbox.
The AutoCompleteTextView is a subclass of EditText class so we can inherit all the properties
of EditText in AutoCompleteTextView based on our requirements.
Following is the pictorial representation of using AutoCompleteTextView in android applications.
Generally, the dropdown list of suggestions can be obtained from the data adaptor and those
suggestions will be appeared only after giving the number characters defined in the Threshold limit.
The dropdown list of suggestions can be closed at any time in case if no item is selected from the list
or by pressing the back or enter key.
In android, we can create an AutoCompleteTextView control in two ways either in the XML layout
file or create it in the Activity file programmatically.
Attribute Description
android:gravity It is used to specify how to align the text like left, right,
center, top, etc.
Create a new android application using android studio and give names
as AutoCompleteTextViewExample. In case if you are not aware of creating an app in android
studio check this article Android Hello World App.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical"
android:id="@+id/linear_Layout">
<AutoCompleteTextView
android:id="@+id/ac_Country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:hint="Enter Country Name"/>
</LinearLayout>
If you observe above code we created AutoCompleteTextView control in XML Layout file.
Once we are done with the creation of layout with required control, 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.autocompletetextviewexample path and write the
code like as shown below.
MainActivity.java
package com.tutlane.autocompletetextviewexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;
Generally, during the launch of our activity, onCreate() callback method will be called by the android
framework to get the required layout for an activity.
Output of Android AutoCompleteTextView Example
When we run above example using the android virtual device (AVD) we will get a result like as shown
below.
This is how we can use AutoCompleteTextView control in android applications to show the list of
suggestions to the user based on the text they entered in the textbox.