0% found this document useful (0 votes)
65 views157 pages

MAD Notes - 4 Units

Android is an open-source operating system used in mobile devices. It was originally developed by Android Inc. and is now owned by Google. The document discusses the history and components of the Android ecosystem, including users, developers, equipment makers, and key features of the Android OS.

Uploaded by

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

MAD Notes - 4 Units

Android is an open-source operating system used in mobile devices. It was originally developed by Android Inc. and is now owned by Google. The document discusses the history and components of the Android ecosystem, including users, developers, equipment makers, and key features of the Android OS.

Uploaded by

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

Unit 1

Android and its Tools

1.1 Introduction to Android

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.

What is Open Handset Alliance (OHA)


The Open Handset Alliance (OHA) is a business alliance that was created for the purpose of
developing open mobile device standards. The OHA is a group of more than 80 companies,
including Google, HTC, Dell, Intel, Motorola, Qualcomm. OHA's main product is the Android
platform - the world's most popular smartphone platform. Android is open to everyone:
developers, designers, and device makers. That means more people can experiment, imagine,
and create the world has never seen.

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.

Categories of Android applications


There are many android applications in the market. The top categories are −

1.2 Need of Android


Why Android?
There are so many reasons you should choose the Android platform for mobile application
development.

1. Zero/negligible development cost


The development tools like Android SDK, JDK, and Eclipse IDE, etc. are free to
download for the android mobile application development. Also, Google
charges a small fee of $25, to distribute your mobile app on the Android Market.
2. Open Source
The Android OS is an open-source platform based on the Linux kernel and
multiple open-source libraries. In this way, developers are free to contribute to
or extend the platform as necessary for building mobile apps which run on
Android devices.
3. Multi-Platform Support
In the market, there is a wide range of hardware devices powered by the
Android OS, including many different phones and tablets. Even the
development of android mobile apps can occur on Windows, Mac OS, or Linux.
4. Multi-Carrier Support
World wide a large number of telecom carriers like Airtel, Vodafone, Idea
Cellular, AT&T Mobility, BSNL, etc. are supporting Android-powered phones.
5. Open Distribution Model
Android Market place (Google Play store) has very few restrictions on the content
or functionality of an android app. So the developer can distribute their app
through the Google Play store and as well other distribution channels like
Amazon’s app store.
Android Ecosystem

Android ecosystem is nothing but the relationship between Users, Developers/Programmers,


and Hardware equipment makers, the Android ecosystem is nothing but the mutual
dependence between Users, Developers, and equipment makers. they are independent of each
other so one cannot exist without the other.

The main block of the android ecosystem is:

1. Android User
2. Developer
3. Equipment Maker

1. Android User (Users buy handsets and software Application):


Android users have more space for customizability for their android devices. Android users are
smarter than other users and they are perceived to have greater levels of support. Android users
are also more likely to prefer saving their cost and love the openness of the platform also they
like to customize their device. Android users are fancier to prefer saving money and also
android user like customizing their android handset/device

2. Developers (sell Application):


Android Developers are the professional software developer in designing applications as well
as developing applications for Android. Some of the following tasks where an android
developer can play his role in the development of android apps:

Design and build advanced applications for the android platform

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 −

Sr.No. Feature & Description

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.

Platform Version API VERSION_CODE


Level

Android 6.0 23 MARSHMALLOW

Android 5.1 22 LOLLIPOP_MR1

Android 5.0 21 LOLLIPOP

Android 4.4W 20 KITKAT_WATCH KitKat for Wearables


Only

Android 4.4 19 KITKAT

Android 4.3 18 JELLY_BEAN_MR2


Android 4.2, 4.2.2 17 JELLY_BEAN_MR1

Android 4.1, 4.1.1 16 JELLY_BEAN

Android 4.0.3, 4.0.4 15 ICE_CREAM_SANDWICH_MR1

Android 4.0, 4.0.1, 14 ICE_CREAM_SANDWICH


4.0.2

Android 3.2 13 HONEYCOMB_MR2

Android 3.1.x 12 HONEYCOMB_MR1

Android 3.0.x 11 HONEYCOMB

10 GINGERBREAD_MR1
Android 2.3.4
Android 2.3.3

9 GINGERBREAD
Android 2.3.2
Android 2.3.1
Android 2.3

Android 2.2.x 8 FROYO

Android 2.1.x 7 ECLAIR_MR1

Android 2.0.1 6 ECLAIR_0_1

Android 2.0 5 ECLAIR

Android 1.6 4 DONUT

Android 1.5 3 CUPCAKE

Android 1.1 2 BASE_1_1

Android 1.0 1 BASE


1.3 Tools and software required for developing an Android Application

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)

Android Studio is a combination of the following components to allow users to


implement android applications.

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.4 Android Architecture


android architecture or Android software stack is categorized into five parts:

1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications

Let's see the android architecture first.

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

• A mobile OS is an operating system for smartphones, tablets, PDAs, or other


mobile devices.
• Mobile OSs combine features of a personal computer OS with other features
useful for mobile or handheld use; usually including, and most of the following
considered essential in modern mobile systems;
Touchscreen, cellular, Bluetooth, Wi-Fi, GPS mobile navigation, camera, video camera,
speech recognition, voice recorder, music player, etc

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:

 Android SDK Build-Tools


 Android Emulator
 Android SDK Platform-Tools
 Android SDK Tools
 Documentation for Android SDK

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.

What Is the SDK Manager?


The Android SDK is composed of modular packages that you can download, install, and update
separately using the Android SDK Manager. The SDK Manager helps to update new SDK
releases and updates whenever a new Android platform is released. The SDK manager can be
found in the top-right corner of the Android Studio screen, as shown below.

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.

2.2 Android Development Tools (ADT)


The android developer tools let you create interactive and powerful application for android
platform.
1. Android Studio
Developed by Google, Android Studio is an all-rounder integrated development
environment that allows the Android developers to get what they desire without an
Integrated Development Environment or IDE.
Android has Gradle-base support that has features like visual layout editor, intelligent code
editor, real-time profilers and APK analyzer. It acts just like any other Java IDE in terms of
error investigating and file hierarchy.
2. Visual Studio – Xamarin

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

The framework based assistance, productivity boosters, unobtrusive intelligence,


duplicates, and inspections are provided with the IDE. Using this IDE, you can do in-
depth coding, quick navigation, and error analysis. It supports mobile app development
with the help of Java, Scala, Kotlin, Groovy.
4. Eclipse IDE

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.

2.3 Android Virtual Devices (AVDs)

An Android Virtual Device (AVD) is a configuration that defines the characteristics of an


Android phone, tablet, Wear OS, Android TV, or Automotive OS device that you want to
simulate in the Android Emulator. The AVD Manager is an interface you can launch from
Android Studio that helps you create and manage AVDs.

To open the AVD Manager, do one of the following:


• Select Tools > AVD Manager.
• Click AVD Manager in the toolbar.
To create a new AVD:
1. Open the AVD Manager by clicking Tools > AVD
Manager
2. Click Create Virtual Device, at the bottom of the AVD Manager dialog.
The Select Hardware page appears

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.

3. Select a hardware profile, and then click Next.


If you don't see the hardware profile you want, you can create or import a hardware
profile.
The System Image page appears.
4. Select the system image for a particular API level, and then click Next.
The Recommended tab lists recommended system images. The other tabs include a
more complete list. The right pane describes the selected system image. x86 images run
the fastest in the emulator.
If you see Download next to the system image, you need to click it to download the
system image. You must be connected to the internet to download it.
5. The Verify Configuration page appears.
Change AVD properties as needed, and then click Finish.
Now you get a new AVD ready for launching your apps on it

2.4 Android Emulator


The Android Emulator is a QEMU-based device-emulation tool that simulates Android devices
on your computer, allowing developers to test applications on different devices and Android
API levels, without needing to have physical devices for each. The emulator comes with
configurations for various Android phones, tablets, Wear OS, and Android TV devices.

The Android emulator provides almost all of the capabilities of a real Android device. You can
perform the following activities:

 simulate phone calls and text messages


 simulate different network speeds
 specify the location of the device
 simulate hardware sensors such as rotation
 access Google Play Store and much more

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.

Difference between JVM and DVM

JVM (Java Virtual Machine) DVM (Dalvik Virtual Machine)


JVM supports multiple operating DVM supports Android operating
systems system only
It is Stack based It is Register based which is designed to
run on low memory.
JVM uses java byte code and runs “.class” DVM uses its own byte code and runs
file having JIT (Just In Time). “.Dex” file. From Android 2.2 SDK Dalvik
has got a Just in Time compiler
It has constant pool for every class. There is constant pool for every
application.
JVM uses java byte code and runs “.class” DVM uses its own byte code and runs
file having JIT (Just In Time). “.Dex” file. From Android 2.2 SDK Dalvik
has got a Just in Time compiler
Here the executable is JAR Here the executable is APK.

2.6 Steps to install and configure Android Studio and SDK

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

• Microsoft windows 7/8/10 (32 or 64 bits)


• Minimum 3GB RAM (recommended 8GB)
• 2GB disk space
• 1280 x 800 minimum screen resolution size
• Intel processor for accelerated emulator
• Android SDK
Note: If you don’t have Android SDK, you can download with Android studio. Go to the
end of download’s page and find android-studio-bundle-162.4069837-windows.exe it
includes SDK also.

Step 2) Run .exe file


Now the next step is to launch .exe file you just download. Following screen will appear

Step 1: Run .exe file

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

Step 10: Done

Click on Finish and start building your Android apps


Unit 3
UI Components and Layouts

3.1 Control Flow

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 −

Sr.No. Folder, File & Description

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

6 This is an auto generated file which contains compileSdkVersion,


buildToolsVersion, applicationId, minSdkVersion, targetSdkVersion,
versionCode and versionName

Following section will give a brief overview of the important application files.

The Main Activity File


The main activity code is a Java file MainActivity.java. This is the actual application
file which ultimately gets converted to a Dalvik executable and runs your application.
Following is the default code generated by the application wizard for Hello
World! application −

package com.example.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Here, R.layout.activity_main refers to the activity_main.xml file located in
the res/layout folder. The onCreate() method is one of many methods that are figured
when an activity is loaded.

The Manifest File


Whatever component you develop as a part of your application, you must declare all
its components in a manifest.xml which resides at the root of the application project
directory. This file works as an interface between Android OS and your application, so
if you do not declare your component in this file, then it will not be considered by the
OS.
Every app includes an Android Manifest file ( AndroidManifest.xml).The manifest file
contains essential information about your app and presents this information to the
Android runtime system. Android must have this information before it can run any of
your app's code.
In this practical you will find and read the AndroidManifest.xml file for the Hello World
app.

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

The Strings File


The strings.xml file is located in the res/values folder and it contains all the text that
your application uses. For example, the names of buttons, labels, default text, and
similar types of strings go into this file. This file is responsible for their textual content.
For example, a default strings file will look like as following file −
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>

The Layout File


The activity_main.xml is a layout file available in res/layout directory, that is
referenced by your application when building its interface. You will modify this file very
frequently to change the layout of your application. For your "Hello World!" application,
this file will have following content related to default layout −
<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" >

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

3.2 Components of a screen

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.

Views and ViewGroups


A View is a widget and is shown on screen like buttons, labels etc. and is derived
from the base class android.view.View. A view is the UI element such as button, label,
text field etc. Anything that you see is a view.
Play VideoThey are grouped and ordered for the appearance and sequence into
an ViewGroup which is derived from android.view.ViewGroup.

Fundamental UI Design

Application components are the essential building blocks of an Android application.


These components are loosely coupled by the application manifest
file AndroidManifest.xml that describes each component of the application and how
they interact.
There are following four main components that can be used within an Android
application −

Sr.No Components & Description

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 −

S.No Components & Description

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.

3.3 Android - UI Layouts

https://www.tutorialspoint.com/android/android_user_interface_la
youts.htm

Android Layout Types


There are number of Layouts provided by Android which you will use in almost all the
Android applications to provide different view, look and feel.

Sr.No Layout & Description

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:

Sr.No Attribute & Description

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.

Margin v/s Padding


During the designing of user interfaces, sometimes there is confusion occurs between
padding and margin. They are used to provide extra space or a gap. Both margin and
padding targets the four sides of an element and can also work without the border
property, but they differ in many ways.

The main difference between the padding and margin is:

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.

1. margin - keep distance on all the four sides


2. marginLeft - keep distance from left side of the view
3. marginRight - keep distance from right side of the view
4. marginTop - keep distance from top of the view
5. marginBottom - keep distance from bottom of the view

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


<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:background="@color/colorPrimaryDark"
android:orientation="vertical"
tools:context="ajitsingh.com.androiduiplayground.DemoActivity">

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

1. padding - keep distance from all the inner boundaries


2. paddingLeft - keep distance from the left inner boundary
3. paddingRight - keep distance from the right inner boundary
4. paddingTop - keep distance from the top inner boundary
5. paddingBottom - keep distance from the bottom inner boundary

Example

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


<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:background="@color/colorPrimaryDark"
android:orientation="vertical"
android:padding="20dp"
tools:context="ajitsingh.com.androiduiplayground.DemoActivity">

<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

Watch this link for the same-


https://www.youtube.com/watch?v=HfKxGr0k8RU

<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">

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

1.Android Linear Layout

Linear Layout Tutorial In Android


Linear layout is a simple layout used in android for layout designing. In the Linear
layout all the elements are displayed in linear fashion means all the childs/elements of
a linear layout are displayed according to its orientation. The value for orientation
property can be either horizontal or vertical.

Types Of Linear Layout Orientation


There are two types of linear layout orientation:
1. Vertical
2. Horizontal
As the name specified these two orientations are used to arrange there child
one after the other, in a line, either vertically or horizontally. Let’s we describe
these in detail.
1.Vertical:
In this all the child are arranged vertically in a line one after the other. In below code
snippets we have specified orientation “vertical” so the childs/views of this layout are
displayed vertically.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"> <!-- Vertical Orientation set -->

<!-- Child Views(In this case 2 Button) are here -->

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

<!-- Child Views(In this case 2 Button) are here -->


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

Main Attributes In Linear Layout:


Now let’s we discuss about the attributes that helps us to configure a linear layout and
its child controls. Some of the most important attributes you will use with linear layout
include:
1. orientation: The orientation attribute used to set the childs/views horizontally or
vertically. In Linear layout default orientation is vertical.
Example: Orientation vertical:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"> <!-- Vertical Orientation set -->

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


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

<!-- Child Views are here -->

</LinearLayout>
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>

Example of Linear Layout:


Now lets design 2 linear layout UI. First we have designed using weight attribute and
second without using it. So below layout output will clear the difference between
them:
2. Android Absolute Layout

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 −

Sr.No Attribute & Description

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.

Example of Absolute Layout in Android:

activity_main.xml (or) main.xml

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

4.Table Layout In Android


Link - https://openplanning.net/12641/android-tablelayout
In Android, Table Layout is used to arrange the group of views into rows and columns.
Table Layout containers do not display a border line for their columns, rows or cells. A
Table will have as many columns as the row with the most cells.

Row and Column in Table Layout Android


A table can also leave the cells empty but cells can’t span the columns as they can in
HTML(Hypertext markup language).

For building a row in a table we will use the <TableRow> element. Table row objects
are the child views of a table layout.

Attributes of TableLayout in Android:


1. id: id attribute is used to uniquely identify a Table Layout.
<TableLayout
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent/>
2. stretchColumns: Stretch column attribute is used in Table Layout to change the
default width of a column which is set equal to the width of the widest column but we
can also stretch the columns to take up available free space by using this attribute. The
value that assigned to this attribute can be a single column number or a comma
delimited list of column numbers (1, 2, 3…n).
If the value is 1 then the second column is stretched to take up any available space in
the row, because of the column numbers are started from 0.
If the value is 0,1 then both the first and second columns of table are stretched to take
up the available space in the row.
f the value is ‘*’ then all the columns are stretched to take up the available space.
<!-- The columns with indexes 0 and 2 will be stretched. -->
<TableLayout
...
android:stretchColumns="0, 2">

...

</TableLayout>

<!-- All columns will be stretched. -->


<TableLayout
...
android:stretchColumns="*">

...

</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

The android:collapseColumns property specifies the columns to be collapsed (collapsed),


meaning its width the column will be 0, the column will be hidden.

<!-- The columns with indexes 0 and 2 will be collapsed-->


<TableLayout
...
android:collapseColumns="0, 2">

...

</TableLayout>

<!-- All columns will be collapsed---->


<TableLayout
...
android:collapseColumns="*">

...

</TableLayout>

5.View - android:layout_column

The android:layout_column attribute is applied to a child View in a TableRow to specify its


column index. Possible values are 0, 1, 2,...
6- View - android:layout_span
The android:layout_span attribute applies to the child View to specify the number of
consecutive cells in a TableRow to be merged together.

Example --Create Login Screen Using Table Layout


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

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

<TableRow android:layout_marginTop="20dip" >

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

<TableRow android:layout_marginTop="20dip" >

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

5.Relative Layout in Android

In android, RelativeLayout is a ViewGroup which is used to specify the position of


child View instances relative to each other (Child A to the left of Child B) or relative to
the parent (Aligned to the top of parent).
Following are the some of most useful layout properties available to views in
RelativeLayout.

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_centerHorizontal If it specified “true”, the view will be horizontally centre aligned


within its 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.

Android Relative Layout Example

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button3" />

<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btn2"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
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

users to edit the text .


4.1 Android TextView Attributes
The following are some of the commonly used attributes related to TextView control in android
applications.

Attribute Description

android: id It is used to uniquely identify the control

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:hint It is used to display the hint text when text is empty

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.

android:text It is used to display the text.

android:textColor It is used to change the color of the text.

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:textSize It is used to specify the size of the text.


android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:textAllCaps It is used to present the text in all CAPS

android:typeface It is used to specify the Typeface (normal, sans, serif, monospace)


for the text.

android:textColor It is used to change the color of the text.

android:textColorHighlight It is used to change the color of text selection highlight.

android:textColorLink It is used to change the text color of links.

android:inputType It is used to specify the type of text being placed in text fields.

android:fontFamily It is used to specify the fontFamily for the text.

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

Create a TextView in Layout File

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<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

XML Attributes of EditText


Attributes Description

android:id It is used to uniquely identify the element

android:width It is used to set the width of EditText in pixels

android:hight It is used to set the height of EditText in pixels

android:text It is used to set the text value inside the EditText

android:inputType It is used to mention what type of value should pass in EditText, like
plain text, email, password, etc

android:hint It is used to highlight what should be input when text is empty

android:gravity gravity is used to align the text like left, right, center, top

android:textSize It is used to specify the size of the text

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:background It is used to set the background of your EditText

android:backgroundTint It is used to set tint to the background of your element

android:maxWidth It is used to set the maximum width of View in pixel

android:minWidth It is used to set the minimum width of View in pixel

android:drawableStart It is used to set the drawable to be drawn to the start of View

android:drawableEnd It is used to set the drawable to be drawn to the end of View

android:drawableBottom It is used to set the drawable to be drawn to the bottom of View

android:drawableLeft It is used to set the drawable to be drawn to the left of View

android:drawableRight It is used to set the drawable to be drawn to the right of View

android:drawablePaddin It is used to set the drawable to be drawn from the set padding of
g View

Example of using EditText


1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:app="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width = "match_parent"
5. android:layout_height = "match_parent"
6. tools:context = "example.javatpoint.com.edittext.MainActivity">
7. <EditText
8. android:id = "@+id/editText"
9. android:layout_width = "wrap_content"
10. android:layout_height = "wrap_content"
11. android:inputType = "text" />
12.
13. </RelativeLayout>

How you retrieve value from EditText in Java Class


Following is the code to retrieve the value from EditText in your Java class.

1. EditText edittext = findViewById(R.id.editText);


2. String value=edittext.getText().toString();

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.

Output of Android Button Example


activity_main.xml

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

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

android:orientation="vertical" android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/fstTxt"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"

android:text="First Number" />

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

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

final EditText firstNum = (EditText)findViewById(R.id.firstNum);

final EditText secNum = (EditText)findViewById(R.id.secondNum);

Button btnAdd = (Button)findViewById(R.id.addBtn);

btnAdd.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

if(firstNum.getText().toString().isEmpty() ||
secNum.getText().toString().isEmpty())

Toast.makeText(getApplicationContext(), "Please fill all the fields",


Toast.LENGTH_SHORT).show();

else {

int num1 = Integer.parseInt(firstNum.getText().toString());

int num2 = Integer.parseInt(secNum.getText().toString());

Toast.makeText(getApplicationContext(), "SUM = " + (num1 + num2),


Toast.LENGTH_SHORT).show();

});

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.

Following is the pictorial representation of using Image Buttons in android applications.

In android, we have different types of buttons available to use based on our requirements, those are
Button, ImageButton, ToggleButton, and RadioButton.

Create ImageButton in XML Layout File

Following is the sample way to define ImageButton control in XML layout file in android application.

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

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

android:orientation="vertical" android:layout_width="match_parent"

android:layout_height="match_parent">

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

Android ImageButton Control Attributes

Following are some of the commonly used attributes related to ImageButton control in android
applications.
Attribute Description

android:id It is used to uniquely identify the control

android:src It is used to specify the source file of an image

android:background It is used to set the background color for an image button


control.

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.

Android Toggle Button


In android, Toggle Button is a user interface control that is used to display ON (Checked) or OFF
(Unchecked) states as a button with a light indicator.

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.

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

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.

Android ToggleButton Control Attributes

The following are some of the commonly used attributes related to ToggleButton control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of toggle button

android:gravity It is used to specify how to align the text like left, right,
center, top, etc.

android:text It is used to set the text.

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:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.


android:background It is used to set the background color for toggle button
control.

android:padding It is used to set the padding from left, right, top and bottom.

android:drawableBottom It’s drawable to be drawn to the below text.

android:drawableRight It’s drawable to be drawn to the right of the text.

android:drawableLeft It’s drawable to be drawn to the left of text.

Output of Android ToggleButton Example


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

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

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

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

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

final ToggleButton tb1 = (ToggleButton)findViewById(R.id.toggle1);

final ToggleButton tb2 = (ToggleButton)findViewById(R.id.toggle2);

Button btnGet = (Button)findViewById(R.id.getBtn);


btnGet.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Toast.makeText(getApplicationContext(), "Toggle Button1 - " + tb1.getText().toString() + "


\n" + "Toggle Button2 - " + tb2.getText().toString(),Toast.LENGTH_SHORT).show();

});

RadioButton & RadioGroup In Android Studio


In Android, RadioButton are mainly used together in a RadioGroup. In RadioGroup
checking the one radio button out of several radio button added in it will
automatically unchecked all the others. It means at one time we can checked only
one radio button from a group of radio buttons which belong to same radio group.

RadioButon is a two state button that can be checked or unchecked. If a radio


button is unchecked then a user can check it by simply clicking on it. Once a
RadiaButton is checked by user it can’t be unchecked by simply pressing on the
same button. It will automatically unchecked when you press any other
RadioButton within same RadioGroup.

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.

Following is the pictorial representation of using RadioButton control in android applications.


** Output of Android RadioButton Example

activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:textSize="18dp"
android:text="Select Your Course"
android:textStyle="bold"
android:id="@+id/txtView"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/rdGroup"
android:layout_below="@+id/txtView">
<RadioButton
android:id="@+id/rdbJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
</RelativeLayout>

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;

public class MainActivity extends AppCompatActivity {


RadioButton android, java, angular, python;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (RadioButton)findViewById(R.id.rdbAndroid);
angular = (RadioButton)findViewById(R.id.rdbAngular);
java = (RadioButton)findViewById(R.id.rdbJava);
python = (RadioButton)findViewById(R.id.rdbPython);

public void onRadioButtonClicked(View view) {


boolean checked = ((RadioButton) view).isChecked();
String str="";
// Check which radio button was clicked
switch(view.getId()) {
case R.id.rdbAndroid:
if(checked)
str = "Android Selected";
break;
case R.id.rdbAngular:
if(checked)
str = "AngularJS Selected";
break;
case R.id.rdbJava:
if(checked)
str = "Java Selected";
break;
case R.id.rdbPython:
if(checked)
str = "Python Selected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
Android CheckBox
Android CheckBox is a type of two state button either checked or unchecked.

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"

android:gravity="right|center_vertical"/> <!-- gravity of the check box-->

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"

android:text="Text Attribute Of Check Box"/> <!--displayed text of the check box-->

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.

** Output of Checkbox program


activity_main.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<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;

public class MainActivity extends AppCompatActivity {

CheckBox android, java, angular, python;

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

ProgressBar Tutorial With Example In Android


Studio

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

Horizontal ProgressBar code:

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>

Let's see a simple example to display progress bar in android.

1. ProgressDialog progressBar = new ProgressDialog(this);


2. progressBar.setCancelable(true);//you can cancel it by pressing back button
3. progressBar.setMessage("File downloading ...");
4. progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
5. progressBar.setProgress(0);//initially progress is 0
6. progressBar.setMax(100);//sets the maximum value 100
7. progressBar.show();//displays the progress bar

Attributes of ProgressBar In Android:

Now let’s discuss important attributes that helps us to configure a Progress bar in xml file
(layout).

1. id: id is an attribute used to uniquely identify a Progress bar.

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

Below we set 100 maximum value for a progress bar.

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"

android:max="100" /><!--set 100 maximum value for the progress bar-->

Set Max Value of ProgressBar In Java Class :

ProgressBar simpleProgressBar=(ProgressBar) findViewById(R.id.simpleProgressBar); // initiate the


progress bar

simpleProgressBar.setMax(100); // 100 maximum value for the progress bar


3. progress: progress is an attribute used in android to define the default progress value
between 0 and max. It must be an integer value.

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"

android:progress="50"/><!--// 50 default progress value-->

Setting Progress Value of ProgressBar In Java Class :

ProgressBar simpleProgressBar=(ProgressBar)findViewById(R.id.simpleProgressBar); // initiate the


progress bar
simpleProgressBar.setMax(100); // 100 maximum value for the progress value

simpleProgressBar.setProgress(50); // 50 default progress value for the progress bar

4. progressDrawable: progress drawable is an attribute used in Android to set the custom


drawable for the progress mode.

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.

Step 1: Add this code in activity_main.xml or main.xml inside layout.

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

android:progressDrawable="@drawable/custom_progress"/><!--custom progress drawable for progress


mode-->

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.

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

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item>

<shape>

<gradient

android:endColor="#fff"
android:startColor="#1f1"

android:useLevel="true" />

</shape>

</item>

</layer-list>

5. background: background attribute is used to set the background of a Progress bar. We


can set a color or a drawable in the background of a Progress bar.

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"

android:background="#000"/><!-- black background color for progress bar-->


6. indeterminate: indeterminate attribute is used in Android to enable the indeterminate
mode. In this mode a progress bar shows a cyclic animation without an indication of
progress. This mode is used in application when we don’t know the amount of work to be
done. In this mode the actual working will not be shown.

In below code we set the indeterminate to true.

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

android:indeterminate="true"/><!--true value for indeterminate-->


Setting indeterminate of ProgressBar In Java class:

ProgressBar simpleProgressBar=(ProgressBar)findViewById(R.id.simpleProgressBar); // initiate the


progress bar

simpleProgressBar.setBackgroundColor(Color.BLACK); // black background color for the progress bar

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

In this example, I'm going to create 2 horizontal ProgressBar(s).

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

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

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

public class MainActivity extends AppCompatActivity {

private ProgressBar pgsBar;

private int i = 0;

private TextView txtView;

private Handler hdlr = new Handler();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

pgsBar = (ProgressBar) findViewById(R.id.pBar);

txtView = (TextView) findViewById(R.id.tView);

Button btn = (Button)findViewById(R.id.btnShow);

btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

i = pgsBar.getProgress();

new Thread(new Runnable() {

public void run() {

while (i < 100) {

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 {

// Sleep for 100 milliseconds to show the progress slowly.

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

ArrayAdapter It will expects an Array or List as input.

CurosrAdapter It will accepts an instance of cursor as an input.

SimpleAdapter It will accepts a static data defined in the resources.


BaseAdapter It is a generic implementation for all three adapter types and it can be
used for ListView, Gridview or Spinners based on our requirements

SimpleAdapter in Android with Example


In Android, whenever we want to bind some data which we get from any data source (e.g.
ArrayList, HashMap, SQLite, etc.) with a UI component(e.g. ListView, GridView, etc.) then
Adapter comes into the picture. Basically Adapter acts as a bridge between the UI
component and data sources. Here Simple Adapter is one type of Adapter. It is basically
an easy adapter to map static data to views defined in our XML file(UI component) and is
used for customization of List or Grid items. Here we use an ArrayList of Map (e.g.
hashmap, mutable map, etc.) for data-backing. Each entry in an ArrayList is
corresponding to one row of a list. The Map contains the data for each row. Now to display
the row we need a view for which we used to specify a custom list item file (an XML file).

General Syntax of SimpleAdapter


SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int
resource, String[] from, int[] to)

4.2 Android Listview

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:

1. id: id is used to uniquely identify a ListView.


Below is the id attribute’s example code with explanation included.
<!-- Id of a list view uniquely identify it-->
<ListView
android:id="@+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

2. divider: This is a drawable or color to draw between different list items.


Below is the divider example code with explanation included, where we draw red color
divider between different views.
<!--Divider code in ListView-->
<ListView
android:id="@+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#f00"
android:dividerHeight="1dp"
/>

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

Android ListView Example

Output of Android ListView Example


activity_main.xml

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

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

public class MainActivity extends AppCompatActivity {

private ListView mListView;

private ArrayAdapter aAdapter;

private String[] users = { "Suresh Dasari", "Rohini Alavala", "Trishika Dasari", "Praveen
Alavala", "Madav Sai", "Hamsika Yemineni"};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mListView = (ListView) findViewById(R.id.userlist);

aAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, users);

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:

1.id: id is used to uniquely identify a 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 id attribute example code for Gridview:


<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

2.numColumns: numColumn define how many columns to show. It may be a integer


value, such as “5” or auto_fit.
auto_fit is used to display as many columns as possible to fill the available space on
the screen.

Important Note: If we don’t specify numColumn property in GridView it behaves like a


ListView with singleChoice.

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

3. horizontalSpacing: horizontalSpacing property is used to define the default horizontal


spacing between columns. This could be in pixel(px),density pixel(dp) or scale
independent pixel(sp).
Below is the horizontalSpacing example code with explanation included where horizontal
spacing between grid items is 50 dp.
<!--Horizontal space example code in grid view-->>
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:horizontalSpacing="50dp"/><!--50dp horizontal space between grid items-->

4.verticalSpacing: verticalSpacing property used to define the default vertical spacing


between rows. This should be in px, dp or sp.
Below is the verticalSpacing example code with explanation included, where vertical
spacing between grid items is 50dp.
<!-- Vertical space between grid items code -->
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:verticalSpacing="50dp"/><!--50dp vertical space set between grid items-
->
5.columnWidth: columnWidth property specifies the fixed width of each column. This
could be in px, dp or sp.
Below is the columnWidth example code. Here column width is 80dp and selected item’s
background color is green which shows the actual width of a grid item.

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;

public class MainActivity extends AppCompatActivity {


GridView gridView;

private String[] numbers = new String[] {


"1", "2", "3", "4", "5",
"6", "7", "8", "9", "10",};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView1);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
}}

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

build good looking and attractive UI based application.

Below is an ImageView code in XML:

Make sure to save lion image in drawable folder

<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

in your xml file.

1. id: id is an attribute used to uniquely identify a image view in android. Below is the

example code in which we set the id of a image view.

<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

to make your layout attractive.


Below is the example code in which we set the source of a imageview lion which is saved

in drawable folder.

<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:src="@drawable/lion" /><!--set the source of an image view-->

/set the source in java class

3. background: background attribute is used to set the background of a ImageView. We

can set a color or a drawable in the background of a ImageView.

Below is the example code in which we set the black color in the background and an image

in the src attribute of image view.


<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:src="@drawable/lion"

android:background="#000"/><!--black color in background of a image view-->

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

all the side’s of a image view.

<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:background="#000"

android:src="@drawable/lion"

android:padding="30dp"/><!--set 30dp padding from all the sides-->

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, center_crop, fitStart etc.


Below is the example code of scale type in which we set the scale type of image view to

fit_xy.

<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:src="@drawable/lion"

android:scaleType="fitXY"/><!--set scale type fit xy-->

Example of ImageView:

Step 1: Create a new project and name it ImageViewExample.

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.

Android ScrollView Example

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

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

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

android:text="Button One" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:layout_marginTop="60dp"

android:text="Button Two" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"
android:layout_marginTop="60dp"

android:text="Button Three" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:layout_marginTop="60dp"

android:text="Button Four" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:layout_marginTop="60dp"

android:text="Button Five" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:layout_marginTop="60dp"

android:text="Button Six" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:layout_marginTop="60dp"

android:text="Button Seven" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:layout_marginTop="60dp"

android:text="Button Eight" />


<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:layout_marginTop="60dp"

android:text="Button Nine" />

</LinearLayout>

</ScrollView>

If you observe above code, we used a ScrollView to enable the scrolling for linearlayout whenever
the content exceeds layout screen.

Output of Android ScrollView Example

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.

Android HorizontalScrollView Example

Now open activity_main.xml file in your android application and write the code like as shown below.

Output of Android HorizontalScrollView Example

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"

android:text="Button One" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button Two" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button Three" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button Four" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button Five" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button Six" />


<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button Seven" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button Eight" />

<Button android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button Nine" />

</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

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

<Button

android:id="@+id/btnShow"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="Show Custom Toast"

android:layout_marginTop="150dp" android:layout_marginLeft="110dp"/>

</LinearLayout>

If you observe above code we created a one Button control in XML Layout file to show the custom
toast notification when we click on Button.

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

custom_toast.xml

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

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

android:id="@+id/custom_toast_layout"

android:orientation="horizontal"

android:layout_width="match_parent"

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;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btnShow);

btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup)


findViewById(R.id.custom_toast_layout));

TextView tv = (TextView) layout.findViewById(R.id.txtvw);

tv.setText("Custom Toast Notification");

Toast toast = new Toast(getApplicationContext());

toast.setGravity(Gravity.CENTER_VERTICAL, 0, 100);

toast.setDuration(Toast.LENGTH_LONG);

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.

Following is the pictorial representation of using a datepicker control in android applications.

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.

Android DatePicker with Calendar Mode

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.

Android DatePicker with Spinner Mode

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.

Following is the example of showing the DatePicker in Spinner mode.

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

Android DatePicker Control Attributes

The following are some of the commonly used attributes related to DatePicker control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:datePickerMode It is used to specify datepicker mode either spinner or


calendar

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

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

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

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="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;

public class MainActivity extends AppCompatActivity {

DatePicker picker;

Button btnGet;

TextView tvw;

@Override

protected void onCreate(Bundle savedInstanceState) {

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

public void onClick(View v) {

tvw.setText("Selected Date: "+ picker.getDayOfMonth()+"/"+ (picker.getMonth() +


1)+"/"+picker.getYear());

});

Output of Android DatePicker Example

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.

Following is the pictorial representation of using a timepicker control in android applications.


Generally, in android TimePicker available in two modes, one is to show the time in clock mode and
another one is to show the time in spinner mode.

Android TimePicker with Clock Mode


We can define android TimePicker to show time in clock format by using
TimePicker android:timePickerMode attribute.

Following is the example of showing the TimePicker in Clock mode.

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

Android TimePicker with Spinner Mode


If we want to show the TimePicker in spinner format like showing hours and minutes separately to
select the time, then by using TimePicker android:timePickerMode attribute we can achieve this.
Following is the example of showing the TimePicker in spinner mode.

<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:id It is used to uniquely identify the control

android:timePickerMode It is used to specify timepicker mode, either spinner or clock

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 TimePicker Example


Following is the example of defining one TimePicker control, one TextView control and
one Button control in RelativeLayout to show the selected time in AM / PM format on Button click in
the android application.

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;

public class MainActivity extends AppCompatActivity {


TimePicker picker;
Button btnGet;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
picker=(TimePicker)findViewById(R.id.timePicker1);
picker.setIs24HourView(true);
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int hour, minute;
String am_pm;
if (Build.VERSION.SDK_INT >= 23 ){
hour = picker.getHour();
minute = picker.getMinute();
}
else{
hour = picker.getCurrentHour();
minute = picker.getCurrentMinute();
}
if(hour > 12) {
am_pm = "PM";
hour = hour - 12;
}
else
{
am_pm="AM";
}
tvw.setText("Selected Date: "+ hour +":"+ minute+" "+am_pm
);
}
});
}
}
If you observe the above code, we are calling our layout using setContentView method in the form
of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we
used file name activity_main and we are trying to show the selected time of TimePicker in AM / PM
format on Button click.

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

Output of Android TimePicker Example


When we run the above example using an android virtual device (AVD) we will get a result like as
shown below.
If you observe the above result, we are getting the time from TimePicker in AM / PM format when we
click on Button in the android application.

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 Threshold property of AutoCompleteTextView is used to define the minimum number of


characters the user must type to see the list of suggestions.

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.

Create AutoCompleteTextView in Layout File


Following is the sample way to define AutoCompleteTextView control in the XML layout file in the
android application.

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="@+id/autoComplete_Country"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
If you observe above code snippet, here we defined AutoCompleteTextView control in xml layout
file.
Android AutoCompleteTextView Attributes
Following are the some of commonly used attributes related to AutoCompleteTextView control in
android applications.

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right,
center, top, etc.

android:text It is used to set the text.

android:hint It is used to display the hint text when text is empty

android:textColor It is used to change the color of the text.

android:textColorHint It is used to change the text color of hint text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of


text.

android:background It is used to set the background color for autocomplete


textview control

android:ems It is used to make the textview be exactly this many


ems wide.

android:width It makes the TextView be exactly this many pixels


wide.
Attribute Description

android:height It makes the TextView be exactly this many pixels tall.

android:textColorHighlight It is used to change the color of the text selection


highlight.

android:fontFamily It is used to specify the fontFamily for the text.

Android AutoCompleteTextView Control Example


Following is the example of defining AutoCompleteTextView control in LinearLayout to bind the
data to defined control using a data adapter and getting the selected list item value in the android
application.

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;

public class MainActivity extends AppCompatActivity {


String[] Countries = { "India", "USA", "Australia", "UK", "Italy", "Ir
eland", "Africa" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, Countries);
AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.i
d.ac_Country);
actv.setThreshold(1);
actv.setAdapter(adapter);
actv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, in
t position, long id) {
Toast.makeText(getApplicationContext(), "Selected Item:
" + parent.getSelectedItem(), Toast.LENGTH_SHORT).show();
}
});
}
}
If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we
used file name activity_main and binding data to
our AutoCompleteTextView using ArrayAdapter and getting selected list item value
using getSelectedItem() method.

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.

You might also like