Android Notes
Android Notes
GPM
[Pick t he date]
Chapter 1. Android and its tools
4) The Open Handset Alliance (DHA) is a business alliance that consists of 47 companiesfor
developing open standard platform for mobile devices
Open Handset
Software Commercializatio
Companie n Companies
s
Android Ecosystem
1] Browser
i) Android browser is one of the best browser on mobile market It generally loads pages
faster
ii) than safari or any other browser has Flash support and simply does everythinga
browser Should do
2] Desktop
The Android phone adds widgets to desktop The purpose for widget.
Eg. the face book widget allows you to update your Fb desktop.
- The people widget allows you to make.
- possible diff actions for different contacts right from your desktop •
-The message widget allows you to immediately see your email from desktop
3] Connectivity
On one page/ desktop you could be able to have 4 connecting device tool button
1) [Turn on/off Bluetooth
2) LTurn on/off mobile
3) LTurn on/off wifi
4] Multi-Notification:
Android phones have multi-notification system with android the app have access to the
notification system and call all report
5] Endless Personalization
The Android cell phone allows client to configure 40x their mobile to look and behave exactly
like they want.
6] Market
Android has an android market.
The android apps are frees and work as well.
Features of Android
Explain features of Android.
1] Open Source
- Android is an open source operating system This way that source code for Androidis
open to Public dissimilar IOS, which is kept secret by Apple.
- This way that anyone can work on OS, not only one company developers.
- Therefore app developers for Android devices are able to implement extra features of
their apps, due to the access they have to contain source code.
- Again these are only some of unique features to Android
- IOS also have many key abilities that are missing on Android device
2] Storage
- SOLite, a light weight relational database is used for data storage purposes.
3] Media Support
Android supports following audio/video/media formats.
- WebM
- H.263
- H.264
- AAC
- HE-AAC
- MPEG-4 SPon Ok
- AMR
- Adobe Flash Streaming CRTMP) and HTTP streaming supported by flash plugin
- Apple HTTP Live Streaming is support through Real Player for Android and the OSfor
duration.
5] Multi-touch
- Android has native support toy media touch which turns initially made available in
handset such as HTC Hero.
- These features has originally disabled at kernel level.
- Google has released an update version for Nexus One and Motorola droid which enables
multi-touch natively.
-
6] Web browser
- The web browser available in Android is based on open SOUT! Web kit layout engine
attached with Chrome's V8 JavaScript engine the browser SCOTOS 100/100 on top of
Acid & fest on Android.
8] Multitasking
- Multitasking of application with unique handling of memory allocation will be existing.
9] Accessibility
Built in text to speech is provided by Talk back for people with low at no version. Enhancement fra
people the heaving disabilities are available as other aids.
- Most Android devices include incrust not and can Yead thicroSD cards Formatted with
FAT32 Ext 307 Ext file system.
- To allow use of high-capacity storage media such as USB flash drive and USBHDD'S
many Android tablets also include USB 'A' receptacle.
- Storage format with FAT 32 is handled by Litus keine VFAT driver, As 3rd party
solutions are necessary to handle other popular file systems NTFS, HFS Plus and ex FAT
such a NIFS,HFS plus.
• Generally to build an application for Android we should have Java Development Kit
(JDK), Android SDK and a development environment.
• The Android SDK is compatible with Windows, Mac and Linux operating systems to
build android applications based on our requirements.
• We can setup android development environment using following two ways:
1. Setup Eclipse IDE Manually (Depreciated)
2. Android Studio.(Android studio for developing mobile application)
• Initially Google supported a Manual Eclipse IDE Setup for android development
environment By downloading required components like Eclipse IDE, Android SDK, Java
Development Kit (JDK) etc. from official site.
• Afterwards Google introduced a component called Android Studio to make environment
setup process simple. Android Studio is the official IDE for Android application
development.
• By using Android Studio bundle we can easily setup android development environment
in any operating system to implement Android applications.
• Android Studio is the combination of components (Eclipse IDE, Android SDK, Android
Virtual Device and Eclipse Plugin) to allow users to implement android applications.
• By downloading Android Studio directly from Google website to setup we can easily
setup development environment.
• Check following steps to know more details about setting up android development
environment to implement required apps using Android Studio.
• The initial android studio setup screen will open like as shown below in that click Next to
continue for further steps of environment setup, (See Fig. 1.5).
Fig 1.5
Fig 1.6
• Now we need to agree the License agreements to proceed further, click on I Agree button
like as shown in Fig. 1.7.
Fig 1.7
Fig 1.8
After selecting the location path to install required components, click Next like as shown in Fig.
1.9.
Fig 1.9
G. P. CO6I [MAD-22617] 10
MIRAJ ( S.
B.
SHINTRE )
• Now select the install menu folder to create a shortcuts for android studio and click
Install like as shown in Fig 1.10.
Fig 1.10
• Once we click Install button the installation process will start and click Next after
completion of installation like as shown in Fig. 1.11.
Fig 1.11
G. P. CO6I [MAD-22617] 11
MIRAJ ( S.
B.
SHINTRE )
• After that it will show installation completion wizard in that click Finish to launch
android studio like as shown in Fig. 1.12.
Fig 1.12
• While launching Android Studio it will give us an option to import settings from previous
version of studio. In case if we don’t have any previous version, select second option and
click OK like as shown in Fig 1.13.
Fig 1.13
Fig 1.14
• Now select a Standard installation type and click Next to install a common settingsand
options like as shown in Fig. 1.15.
Fig 1.15
G. P. CO6I [MAD-22617] 13
MIRAJ ( S.
B.
SHINTRE )
• Now verify settings and click Finish to complete android studio setup process like as
shown in Fig. 1.16.
Fig 1.16
Fig 1.17
G. P. CO6I [MAD-22617] 14
MIRAJ ( S.
B.
SHINTRE )
• After completion of all required components installation we will be able to see Android
Studio welcome window like as shown in Fig. 1.18.
Fig 1.18
• This is how we can setup android development environment on windows machine whichis
having Windows 10 operating system using android studio IDE.
G. P. CO6I [MAD-22617] 15
MIRAJ ( S.
B.
SHINTRE )
1.4 Android Architecture.
• The Android OS can be referred to as software stack of diff layers, where every layer is
group of several program components
• It includes –
1. Operating systems
2. middle ware
3. Key applications
1. Applications
2. Application framework
3. Libraries
4 Android runtime
5 Linux kernel
Application Framework:
• Android, being open, offers developers the ability to build extremely rich and innovative
application Developers are free to take benefit of the device hardware, access location
information, run set alarm background services, add notifications to the status bar, and
much, much more.
• Developers have full access to the same framework APIs used by the coreapplications.
The application architecture is designed to simplify the reuse of components, any
application can publish its capabilities and any other application may then make use of
those capabilities. They can also be replaced by the user.
1. Activity Manager: This layer manages the lifecycle of applications and provides a common
navigation back stack.
2. Window Manager: As the name suggest it manages the window surface. Then it organithe
screen layout and locates the drawing surface and also performs other windows related jobs.
3. View Manager: Views the window.
4. Contents Manager: Enables applications access data from other applications or to their own
data.
5. Notification Manager: We get the notification from the system when the battery is tow. If the
programmer wants, he can also enable all applications to display customer alerts in the statusbar.
6. Package Manager: This manager the other packages if it is instant in the machine.
Sometimes we may download some application which is not own. This manages otherpackage.
7. Telephony Manager: Telephony manager is to handle the receiver call or voice calls.
8. Resource Manager: This manager provides access to the non-code resources(Graphics
localized string, and layout files) .
9. Location Manager: This manager helps to locate the mobile devices at which the location of
the mobile device can be searched. Ex- Map, GPS or cell tower.
10. XMPP Service Manager: Every mobile has some service like music applications, browser,
ringtones, services etc. It is managed by service manager.
Libraries:
The 3 layer of android architecture is the libraries layer. The color of this layer is green; it
means it is written in C and C++ libraries.
This layer contents 9 components. This layer is communicated through application
framework layer. The communication happens through the Java Native Interface(JNI)
package.
This package of Java is represented for communication C and C++ language.
Following are the 9 major components:
Surface Manager
Open GLIES
SQLite database
Media Framework
SGL(Scalable graphics libraries)
Free Type
SSL (Secured socket layer)
Web kit
lib c(C libraries)
Open GLIES: This component provides mostly 3D graphics libraries which have to be
implemented by Java application and it is rended by the application layer when they want some
3D graphics:
SQLite: When our application wants to connect the database then we can think of some popular
RDBMS like mySQL, Oracle. But they are heavy weight database server as our applications are
light weight. So it is better to have light weight RDBMS.
So we can use SQLite which is an open source RDBMS. It is not exactly tiewith
android.
We can also use file system to store the data.
Media Framework: When we are using any mobile set, what comes our mind are
Picture quality should be good.
Multimedia action should good which include the sounds
So to get those activities or application Android API has to call the media framework
component to play and view the video-audio.
SGL (Scalable graphics libraries): It is responsible for implementing low level graphics by
using JNI.
Free type: It is the responsible for to support the font quality, the image (bitmapimages).
SSL (Secured socket layer): It stands for secure socket layer. It is mostly used in internal
application. Suppose online through mobile we want to access our online through mobile then at
that time we need some secure socket layer. It is also required in case of chat and message.
It supports http and top protocol.
Webkit: It is responsible for giving the browser supports. It also support well to following s/w-
• Google Chromes
• Apple Safari
• It also supports JavaScript, jQuery, HTML, CSS. Ajax
Lib c: It stands for C libraries When we want to access some code C libraries headers then this
components is useful.
Android Runtime:
• Android Runtime consists of Dalvik Virtual Machine and Core Libraries.
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.
G. P. CO6I [MAD-22617] 24
MIRAJ ( S.
B.
SHINTRE )
2.1 Operating system, Java JDK, Android SDK
Operating system
MAC
• MOCOS X(Intel) 10.5.8(X 86only)
Windows
• Window XP(32bit)
• Vista(32/64bit)
• Window 7(32/64bit)
G. P. CO6I [MAD-22617] 25
MIRAJ ( S.
B.
SHINTRE )
Which as help you to build, test and debug apps of android.
Android SDK can be downloaded from http://developer.android.com/SDK/index.html
using android SDK manager which is free.
We find the Android SDK in a zip file and have to unzip its contents(android-sdk- windows)
into folder(c:\android \folder name)
Wecan also create Android virtual Devices(SDK)which runin emulator
Android SDK is made up of 2 main parts.
• Packagesaretherecordsspecifictoa
particular version of android (called
Package: platform)orparticularadd-ontoa
platform.
Android SDK
contains
G. P. CO6I [MAD-22617] 26
MIRAJ ( S.
B.
SHINTRE )
o GSM, EGDE and 3G network or data transfer allows you to make or receive calls or
SMSmessage. Otherwise sendandreceive data acrossmobile Network.
o Comprehensive API’s designed for location-based services such as GPS.
o Full multimedia HWcontrol together withplaybackand recordingusing camera
and microphones
o API’s designed for accelerometer and compass HW.
o IPC message passing.
o Shared data store
o An integrated open source Webkit-based browser
o Fullsupportforapplicationthatintegratemapcontrolaspartoftheiruser interface.
o Peer-to-peer(2p2) support using Google Talk
o Mobile optimized hardware accelerated graphics including a path=based 2D graphics
library and support for 3D graphics usingopen GLI ES.
o Medialibrariesdesigned for playingandrecording varietyofaudio /videoor still
image formats.
o An application framework that encourage reuse of application component and
replacement of native application.
G. P. CO6I [MAD-22617] 27
MIRAJ ( S.
B.
SHINTRE )
2.2 Android Development Tools (ADT)
o Android development tools (ADT) is plugin for Eclipse or Android Studio which
providessuitableenvironmenttodevelopanAndroidapplication.
o Due to ADT creation, compilation and debugging are possible.
o ADT can able to setup new Android projects, create an application UI, insert package
basedonandroid framework API, debug (orclear up) yourapplicationsusing
AndroidSDKtoolsandexportsignedorunsigned.apkfiles in order to distribute
applications
Android Studio
ThisistheofficialIDEforandroid,makingitnumberonechoiceforthe majorityof
developers looking to make basic apps in keeping with Google’s material designandwith
access toallthe advancedfeatures oftheplatform.
Eclipse
Following are the steps to develop application using Eclipse IDE
1. Install the JDK
2. Download and install Eclipse
3. Download and install Android SDK
4. Install the ADT plugin for Eclipse
5. Configure the ADTplugin
6. Create the AVD
7. Create the Hello World Android application
G. P. CO6I [MAD-22617] 28
MIRAJ ( S.
B.
SHINTRE )
Some toolsincluded
Android Debug Bridge (ADB)
AndroidStudioincludesADB,Whichisacommandlinetoolorbridgeof
communicationbetweenAndroidDevicesandothercomputersthatcan beused
duringdevelopmentandtheoveralldebuggingandQAprocess
AVD manager
TheAVDmanagerisanemulatorusedtorunandroidappsoncomputer.
Fabric
GameMaker studio
For android game app developers, oneof the mostpopular development tool is
GameMaker:Studio. It provides everything you need to create 2D games using
very little code.
IntelliJIDEA
Gradle
Gradle is one of the most popular development tools for creating large scale
applications.
G. P. CO6I [MAD-22617] 29
MIRAJ ( S.
B.
SHINTRE )
2.3 Android Virtual Devices (AVDs)
A hardwareprofile:
• Definesthehardwarefeaturesofthevirtualdevice. Forexample.Youcandescribe whetherthe
devicehasacamerawhetheritusesaphysicalQWERTYKeyboardora dialing pad, now
much memory it have and so on
Adedicatedstorageareaonyourdevelopmentmachine:
• Thedevice'suserdata(installedapplicationssettings,andsoon)anemulatedSD card are
stored in this area.
WhileselectinganimageforAVD.,refertothebelowpoints:
• The API Level of the goal is important. because our application will not be able to run on a
systemasspecifiedintheminsdkVersion attributeofthemanifestfileof that application.
• CreateatleastoneAVDthatusesatarget whoseAPILevelisgreaterthanthat required by
our application. The downloaded application compatibility of users receive a system update
and normally it will continue to function which is ensured by forward – Compatibility (because
itallowsusto test the forward - compatibility of our application).
G. P. CO6I [MAD-22617] 30
MIRAJ ( S.
B.
SHINTRE )
Android AVDdiagram
• Selecttools AVDManager.ClickAVDManager,AVD
Manager icon in the toolbar
G. P. CO6I [MAD-22617] 31
MIRAJ ( S.
B.
SHINTRE )
• Nowclickthe+CreateVirtualDevice…button.Thiswill bring
upVirtualDeviceConfigurationDialog.
• Selectanydeviceyouwant,thenclickNext.
G. P. CO6I [MAD-22617] 32
MIRAJ ( S.
B.
SHINTRE )
• ChooseAndroid Version,thenclick Next.
G. P. CO6I [MAD-22617] 33
MIRAJ ( S.
B.
SHINTRE )
• NowyouhavegotanewAVDreadyforlaunchingyour
apps on it.
G. P. CO6I [MAD-22617] 34
MIRAJ ( S.
B.
SHINTRE )
2.4 Emulators
Emulators
o AndroidEmulatorsareresponsibleforrunning,debuggingandtestingthe Android
application
o The AndroidemulatorsimulatesAndroiddevicesonyourcomputersothat can test
your application on a variety of devices and Android API levels without needing to
have each physical device.
o The emulator provides almost all of the capabilities ofa realandroid device. Youcan
simulate incoming phone calls, and text messages, specify location of device, simulate
different network speeds, simulate rotation and other hardwaresensors, access
the google play store and much more.
o The Android SDK comes with a virtual mobile device emulator that runs on the
computer.
o TheAndroidemulatormimicsallthehardware andsoftwarefeaturesof typical
mobiledevices,exceptthatitcannotplaceannualphonecalls
o It provides a selection of navigation and control keys which we can press using a
mouseorinputfromkeyboardtogenerateeventsandperformactions respectively.
o It runs onacomplete Android system stack down to the kernel level
o We can selectversionofandroidsystem wewish torunin the emulatorby
configuring the AVDs
o We canalso modifythe deviceskin and keymappingsaccording toour
convenience
o Whilelaunchingtheemulatoratruntime,wecanuseavarietyofcommands and
options to control its behavior.
Theandroidemulatorsupportsmanyhardwarefeatureslikelytobe found on
mobile devices including
G. P. CO6I [MAD-22617] 35
MIRAJ ( S.
B.
SHINTRE )
Requirements andrecommendations
Launch theemulator
Android Emulator
Let’sseethecompilingandpackagingprocessfromthesourcefile
G. P. CO6I [MAD-22617] 37
MIRAJ ( S.
B.
SHINTRE )
o And generates .apk executablefile.
JV DVM
• TheexecutableformatofJVMisJAR • TheexecutableformatofDVMisAPK
G. P. CO6I [MAD-22617] 38
MIRAJ ( S.
B.
SHINTRE )
2.6 Stepstoinstallandconfigureandroidstudioand SDK
G. P. CO6I [MAD-22617] 39
MIRAJ ( S.
B.
SHINTRE )
Steps to install android studio
Run asAdministrator
G. P. CO6I [MAD-22617] 40
MIRAJ ( S.
B.
SHINTRE )
SelectandroidvirtualdeviceGoto
next
G. P. CO6I [MAD-22617] 41
MIRAJ ( S.
B.
SHINTRE )
Click oninstall
Installation in progress
G. P. CO6I [MAD-22617] 42
MIRAJ ( S.
B.
SHINTRE )
Click onfinish
Welcome screen
G. P. CO6I [MAD-22617] 43
MIRAJ ( S.
B.
SHINTRE )
Selectinstallationtype
Select uitheme
G. P. CO6I [MAD-22617] 44
MIRAJ ( S.
B.
SHINTRE )
Confirmationwizard
Downloadandsetupenvironment
automatically
G. P. CO6I [MAD-22617] 45
MIRAJ ( S.
B.
SHINTRE )
Steps to configure android SDK
SelectdesierdSDKPlatform
G. P. CO6I [MAD-22617] 46
MIRAJ ( S.
B.
SHINTRE )
Install all SDk tools
G. P. CO6I [MAD-22617] 47
MIRAJ ( S.
B.
SHINTRE )
Ch.3: UI Components and Layouts
Syllabus:
G. P. CO6I [MAD-22617] 48
MIRAJ ( S.
B.
SHINTRE )
3.1 Control flow
G. P. CO6I [MAD-22617] 49
MIRAJ ( S.
B.
SHINTRE )
Step 4 : Select your SDK to and click next Target Android Device
G. P. CO6I [MAD-22617] 50
MIRAJ ( S.
B.
SHINTRE )
Step5:Toaddtheprojectunmobileselecttheproperactivityhereweselecttheempty activityand
click Next
The differ components of UI just split the Android windo into parts and give some numbering
Menu Bar : Menu Bar contains the drop-down menus to perform different functions.
Navigation Bar: Navigation Bar shows the selected file hierarchy which helps developer to directly
navigate to the parent directories of the file or switchbetween different files.
G. P. CO6I [MAD-22617] 51
MIRAJ ( S.
B.
SHINTRE )
Tool Buttons Bar: Tools Buttons bar allows to switch between different tools in different windows
(Project Tool, Preview, Console Windows).
Project Tool Window: There are three project tool windows in the interface which allows developer to
use indifferent ways. Project ToolWindowin theleft sideallows developer tonavigate through allthe
tools provided in the left side Tool Buttons such as Project hierarchy view, Favourites. Structure view
etc.Right side Project Tool Window allows to navigate between the right Tool Buttons like Application
Interface Preview ondifferent devices, Gradlefunctions etc. Bottom Project ToolWindowallows to
navigate between the bottom Tool Buttons like Terminal, Run. Android etc.
EditorWindow:Editorwindowopentheselectedfiletoallowsdevelopertoeditthemasperthe
requirements.
Status Bar: The status bar displays informational messages about the project and the activities of
Android Studio. It also contain a button in the left corner which lists all the tools menu button.
Hovering over items or button in thestatus bar will provide a description of that field.
G. P. CO6I [MAD-22617] 52
MIRAJ ( S.
B.
SHINTRE )
3.2 Directory Structure:
Here a new Android project application is created.
There are various files that form an Android project in the Package Explorer in eclipse. The various
Folders and their files are as follows:
STC: This folder contains the java source files for the project .In this example, there is one file
AndroidProjectActivity.java .The AndroidProject Activity. java. is the source file for the activity. we
write the code for this application in thisjava file. The java file is listed under the package name ie.
com.pkg. Example for the project.
gen: This folder contains the R.java file, which is generated by the compilerthat references all the
resources found in this project. We cannot modifythis File. All the resources in thisproject are
automatically compiled into this class hence we can transfer to them using the class.
Android 2.2 libraries: This thing contains one file, android.jar, whichcontainsall the class libraries
needed for an Android Application.
Assets: Folder contains all the resources used by this application, such asHTMLtext files, databases, etc.
Bin: This folder contains the Files built by the ADT during the CompilationItgenerates the .apkfile. An
.apkfile is the application binary of an Androidapplication. It contains the entire things needed to run
an android application
Res: This folder contains all the resources files such as pictures, XML filesfordefining layout used in this
application.
Android Manifest.xml: This is the manifest file for this Android project Itcontains information about the
Android application such as minimum Android version, permission to access Android device
capabilities such as internet access permission, ability to use phone permission,etc..
Main.xml: The main.xml file defines the user interface for activity
Layout: contains XML layout files, Layout files are XML files which definehowvarious Android objects
are organized on the screen.
Values: XML Files which stores various string values (titles, labels,etc)
G. P. CO6I [MAD-22617] 53
MIRAJ ( S.
B.
SHINTRE )
3.3 Component of a screen & Fundamentals UI Design:
Component of a screen
An activity displays the user interface of our application, which may contain widgets like buttons,
Image buttons, text boxes, labels.etc. Typically, you define your UI using an xml file (for example,
activity_main.xml file located in the res then inside afolder called layout) which may look like
This:
activity-main.xml
<TextView
</LinearLayout>
During this runtime, we can load the xml UI in the onCreate() event handler in our Activity class, using
The setContentView() method of the Activity class.
@Override
During compilation time, each element in the XMLfile is compiled into its equivalent Android GUI
Class, with an attribute represented by methods The android system then Creates the user Interface
(UI) of the Activity when it is loaded
G. P. CO6I [MAD-22617] 54
MIRAJ ( S.
B.
SHINTRE )
3.4 Fundamentals UI Design:
Every item in auser interface is a subclass of the Android View Class which is present inside the
package (android.view)The Android SDK provider a can be used to set of pre-built views that can be
used to construct a user. Interface
Views:
Views are the base class for all visual interface elements.
View Groups:
View Groups are extensions of the view class that can contain multiple Child views, In order to Extend
the View Group class to create compound controls made up of interconnected ChildViews
The View Group class is also extended to provide the layoutmanager that help us to control layout
withinouractivitiesA View Group provides the layout in which we can order the appearanceand
sequence of views.
Fragments:
Fragments, introduced in Android 3.0 which uses APF Level 11 are used to encapsulate portions of our
UI
Activities
Activities dictate the UI and handle the user interaction to the smart phone screen.
Activities are the Android equivalent of Forms in traditional windows desktop development
G. P. CO6I [MAD-22617] 55
MIRAJ ( S.
B.
SHINTRE )
3.5 Linear Layout; Absolute Layout; Frame Layout; Table Layout; Relative Layout
UI layouts :
All elements in the layout are built using a hierarchy of View and View Group
objects.
A View usually draws something the user can see and interact with.
Whereas A View Group is an invisible container that defines the layout structure for View and other
1.Linear Layout
2.Absolute Layout
3.Frame Layout
4.Table Layout
5.Relative Layout
G. P. CO6I [MAD-22617] 56
MIRAJ ( S.
B.
SHINTRE )
1. Linear Layout:
Android Linear Layout is a view group that aligns, all children in either vertically or horizontally.Linear
Layoutissimpleandeasytouse,itcreatesascrollbar,ifthelengthof thewindowexceedsthelength
of the screen.Linear Layout are one of the simplest and common type of layouts used by
androiddevelopers to keepcontrols within theirinterfaces.The linear layout works asmuch as its
name implies, it organizes the controls either a verticalor horizontal pattern.
Example :
Linear layout can be defined within XML layout resources or programmatically in the applications Java
code.
G. P. CO6I [MAD-22617] 57
MIRAJ ( S.
B.
SHINTRE )
Layout_width : Used to set the width of the given control. This property has following options:-
wrap_content andmatch_parent
Layout_height : Used to set the height of the given control. This property has following options:-
wrap_content andmatch_parent
LinearLayout(context context)
Program :
activity_main.xml
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name : John || "
android:textColor="@color/black"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Marks : 92%"
android:textColor="@color/black”/>
</LinearLayout>
MainActivity.java
G. P. CO6I [MAD-22617] 58
MIRAJ ( S.
B.
SHINTRE )
package com.example.exp4_exefcise_que2;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle;
public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Output :
G. P. CO6I [MAD-22617] 59
MIRAJ ( S.
B.
SHINTRE )
2. Absolute Layout:
Absolute layout is based on the simple idea of placing each control at an absolute position.
We specify for the exact x and y co-ordinates on the screen for every control.Absolute layout is less
flexible.It is harder to maintain than other types of layouts without absolute positioning.
Example :
(15,25)
(80,50)
component
Layout_width : Used to set the width of the given control. This property has following options:-
wrap_content andmatch_parent
Layout_height : Used to set the height of the given control. This property has following options:-
wrap_content andmatch_parent
G. P. CO6I [MAD-22617] 60
MIRAJ ( S.
B.
SHINTRE )
Layout_x: Componentadded at given xposition
AbsoluteLayout(context context)
Program :
activity_main.xml
<AbsoluteLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
G. P. CO6I [MAD-22617] 61
MIRAJ ( S.
B.
SHINTRE )
</AbsoluteLayout>
MainActivity.java
package com.example.exp5_exercise_que2;
importandroid.support.v7.app.AppCompatActivity; importandroid.os.Bundle;
Output :
G. P. CO6I [MAD-22617] 62
MIRAJ ( S.
B.
SHINTRE )
3. Frame Layout:
The purpose of the frame layout is to allocate an area of screen. Frame layout is used for displaying a
single view.Generally, frame layout should beused tohold a single child view, because it can be
difficult to organize child views in awaythat’s scalable to different screen size without the children
overlapping each other.
android:foreground – This defines the drawable to draw over the content and possible values may be
a
FrameLayout(context context)
Program :
activity_main.xml
<FrameLayout 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:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
G. P. CO6I [MAD-22617] 63
MIRAJ ( S.
B.
SHINTRE )
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:textSize="17dp"
android:textStyle="bold" android:textColor="@color/black"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Integer"
android:textColor="@color/black"
android:textSize="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="80dp”/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" a
ndroid:textColor="@color/black"
android:text="Float"
android:textSize="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="110dp"
/>
G. P. CO6I [MAD-22617] 64
MIRAJ ( S.
B.
SHINTRE )
</FrameLayout>
MainActivity.java
package com.example.exp6_exercise_que2;
Output
G. P. CO6I [MAD-22617] 65
MIRAJ ( S.
B.
SHINTRE )
4. Table Layout:
<TableLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width="match_parent"
android:layout_height="match_parent"
<TableRow>
<TextView
android:text="Name"
android:textSize="23dp"
/>
<TextView
android:text="Marks"
android:textSize="23dp"
/>
</TableRow>
</TableLayout>
Android table layout going to be arranged groups of views into rows and columns.
You will use the <TableRow> element to build a row in the table.
Each row has zero or more cells; each cell can hold one view object. Table layout
containers do not display border lines for their rows, columns, or cells.
G. P. CO6I [MAD-22617] 66
MIRAJ ( S.
B.
SHINTRE )
Example:
Row 1
Row_ Row_
3 3
Col_1 Col_2
G. P. CO6I [MAD-22617] 67
MIRAJ ( S.
B.
SHINTRE )
Attributes of table layout:
1. TableLayout(context context)
Creates a new TableLayout for the given
Program activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textStyle="bold"
android:textSize="23dp"
android:layout_marginLeft="8dp”/>
<TextView
G. P. CO6I [MAD-22617] 68
MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Marks"
android:textStyle="bold"
android:textSize="23dp"
android:layout_marginLeft="8dp”/>
</TableRow>
<TableRow>
<TextView
android:text="Rutuja"
android:textSize="14dp"
android:layout_marginLeft="8dp"/>
<TextView
android:text="88"
android:textSize="14dp"
android:layout_marginLeft="8dp"/>
</TableRow>
<TableRow>
<TextView
android:text="Aryan"
android:textSize="14dp"
android:layout_marginLeft="8dp"/>
<TextView android:text="94"
android:textSize="14dp"
android:layout_marginLeft="8dp"/>
</TableRow>
G. P. CO6I [MAD-22617] 69
MIRAJ ( S.
B.
SHINTRE )
</TableLayout>
MainActivity.java
package com.example.exp6_exercise_que1;
} }
Output :
G. P. CO6I [MAD-22617] 70
MIRAJ ( S.
B.
SHINTRE )
5. Relative Layout:
The relative layout enables you to specify how child views are positioned relative to each other.
<RelativeLayout
</RelativeLayout>
The position of each view can be specified as relative to sibling elements or relative to the present.
Example:
1) Android:id
G. P. CO6I [MAD-22617] 71
MIRAJ ( S.
B.
SHINTRE )
2) Android:gravity
3) Android:ignoreGravity
4) Android:layout_above
5) Android:layout_alignBottom
6) Android:layout_alignLeft
7) Android:layout_alignParentBottom
8) Android:layout_alignParentEnd
9) Android:layout_alignParentLeft 10.Android:layout_alignParentRIght
Program activity_main.xml
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
G. P. CO6I [MAD-22617] 72
MIRAJ ( S.
B.
SHINTRE )
android:text="BLUE"
android:textSize="10dp"
android:layout_alignParentTop="true”/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RED"
android:textSize="10dp"
android:layout_alignParentBottom="true”/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GREEN"
android:textSize="10dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
MainActivity.java
package com.example.exp6_extraque;
Output :
G. P. CO6I [MAD-22617] 73
MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 74
MIRAJ ( S.
B.
SHINTRE )
Extra Programs related to Layouts
1.LinearLayout:
<TextView
android:id="@+id/student_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NAME : AROHI AJAY PATEL"
android:textSize="25dp"
android:textColor="#0023FF"
android:layout_marginTop="100dp"
android:layout_gravity="center"
android:textStyle="bold|italic"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AGE : 24"
android:textSize="25dp"
android:textColor="#FF5722"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:textStyle="bold|italic"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOBILE NUMBER : 9999988888"
android:textSize="25dp"
android:textColor="#0A5A0D"
G. P. CO6I [MAD-22617] 75
MIRAJ ( S.
B.
SHINTRE )
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:textStyle="bold|italic"/>
</LinearLayout>
Output:
G. P. CO6I [MAD-22617] 76
MIRAJ ( S.
B.
SHINTRE )
2..LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffb3"
tools:context=".MainActivity">
<TextView
android:layout_width="360dp"
android:layout_height="55dp"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:textAppearance="@style/TextAppearance.AppCompat.Display3"
android:textColor="@color/colorAccent"
android:textSize="40dp" />
<TextViewandroid:layout_width="match_parent
" android:layout_gravity="bottom"
android:layout_height="30dp"
android:layout_marginTop="50dp"
android:textColor="#669999" />
G. P. CO6I [MAD-22617] 77
MIRAJ ( S.
B.
SHINTRE )
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/t1"
/>
<TextView
android:layout_width="match_parent"
android:layout_gravity="bottom"
android:layout_height="30dp"
android:layout_marginTop="20dp"
android:text=" PASSWORD:"
android:textColor="#669999" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/t2"/>
<Button
android:id="@+id/b1"
android:layout_width="230dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:backgroundTint="#ffcc00"
android:onClick="submit1"
android:text="Submit"
G. P. CO6I [MAD-22617] 78
MIRAJ ( S.
B.
SHINTRE )
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#001a00"
android:textSize="30dp"
android:layout_marginTop="20dp"
android:background="@drawable/rounded_corners"
android:visibility="visible"
/>
</LinearLayout>
Output:
G. P. CO6I [MAD-22617] 79
MIRAJ ( S.
B.
SHINTRE )
3. Absolute Layout
<AbsoluteLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@drawable/wallpaper"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="59dp"
android:layout_height="63dp"
android:layout_x="293dp"
android:layout_y="74dp"
android:text="05"
android:textColor="#000000"
android:textSize="50dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
G. P. CO6I [MAD-22617] 80
MIRAJ ( S.
B.
SHINTRE )
android:layout_x="292dp"
android:layout_y="124dp"
android:text="48"
android:textColor="#000000"
android:textSize="50dp"
/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="310dp"
android:layout_y="190dp"
android:text="PM"
android:textColor="#000000" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="8dp"
android:layout_y="645dp"
app:srcCompat="@android:drawable/ic_menu_call" />
<ImageView
android:id="@+id/imageView2"
G. P. CO6I [MAD-22617] 81
MIRAJ ( S.
B.
SHINTRE )
android:layout_width="53dp"
android:layout_height="45dp"
android:layout_x="363dp"
android:layout_y="633dp"
app:srcCompat="@android:drawable/ic_menu_camera" />
<ImageView
android:id="@+id/imageView3"
android:layout_width="49dp"
android:layout_height="39dp"
android:layout_x="282dp"
android:layout_y="307dp"
app:srcCompat="@drawable/fb" /
<ImageView
android:id="@+id/imageView4"
android:layout_width="48dp"
android:layout_height="37dp"
android:layout_x="216dp"
android:layout_y="356dp"
app:srcCompat="@drawable/chrome" />
<ImageView
android:id="@+id/imageView6"
android:layout_width="51dp"
android:layout_height="40dp"
G. P. CO6I [MAD-22617] 82
MIRAJ ( S.
B.
SHINTRE )
android:layout_x="341dp"
android:layout_y="357dp"
app:srcCompat="@drawable/twitter" />
<ImageView
android:id="@+id/imageView7"
android:layout_width="47dp"
android:layout_height="39dp"
android:layout_x="281dp"
android:layout_y="394dp"
app:srcCompat="@drawable/whatsapp" />
<ImageView
android:id="@+id/imageView8"
android:layout_width="66dp"
android:layout_height="48dp"
android:layout_x="209dp"
android:layout_y="436dp"
app:srcCompat="@drawable/instagram" />
<ImageView
android:id="@+id/imageView9"
android:layout_width="46dp"
android:layout_height="41dp"
android:layout_x="345dp"
android:layout_y="439dp"
G. P. CO6I [MAD-22617] 83
MIRAJ ( S.
B.
SHINTRE )
app:srcCompat="@drawable/pinterest" />
<ImageView
android:id="@+id/imageView10"
android:layout_width="34dp"
android:layout_height="33dp"
android:layout_x="291dp"
android:layout_y="482dp"
app:srcCompat="@drawable/linkedin" />
<ImageView
android:id="@+id/imageView11"
android:layout_width="37dp"
android:layout_height="39dp"
android:layout_x="192dp"
android:layout_y="636dp"
app:srcCompat="@drawable/lock" />
<ImageView
android:id="@+id/imageView12"
android:layout_width="42dp"
android:layout_height="45dp"
android:layout_x="218dp"
android:layout_y="514dp"
app:srcCompat="@drawable/camera" />
<ImageView
G. P. CO6I [MAD-22617] 84
MIRAJ ( S.
B.
SHINTRE )
android:id="@+id/imageView13"
android:layout_width="65dp"
android:layout_height="48dp"
android:layout_x="336dp"
android:layout_y="518dp"
app:srcCompat="@drawable/maps" />
<ImageView
android:id="@+id/imageView14"
android:layout_width="52dp"
android:layout_height="43dp"
android:layout_x="280dp"
android:layout_y="554dp"
app:srcCompat="@drawable/music" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="81dp"
android:layout_x="17dp"
android:layout_y="324dp"
android:rotation="270"
android:text="26.2021"
android:textColor="#fff"
android:textSize="20dp"
android:textStyle="bold" />
G. P. CO6I [MAD-22617] 85
MIRAJ ( S.
B.
SHINTRE )
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="-35dp"
android:layout_y="406dp"
android:rotation="270"
android:text="MONDAY"
android:textColor="#fff"
android:textSize="50dp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="36dp"
android:layout_y="459dp"
android:rotation="270"
android:text="APRIL"
android:textColor="#A6FFFFFF"
android:textSize="70dp" />
<ImageView
android:id="@+id/imageView15"
G. P. CO6I [MAD-22617] 86
MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="69dp"
android:layout_y="91dp"
app:srcCompat="@drawable/user" />
</AbsoluteLayout>
Output:
G. P. CO6I [MAD-22617] 87
MIRAJ ( S.
B.
SHINTRE )
G. P. CO6I [MAD-22617] 88
MIRAJ ( S.
B.
SHINTRE )
4. Table Layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#000000">
<TableRow android:layout_marginTop="300dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="1"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
G. P. CO6I [MAD-22617] 89
MIRAJ ( S.
B.
SHINTRE )
android:text="2"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="3"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
</TableRow>
<TableRow android:layout_marginTop="25dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="4"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
G. P. CO6I [MAD-22617] 90
MIRAJ ( S.
B.
SHINTRE )
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="5"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="6"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
</TableRow>
<TableRow android:layout_marginTop="25dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
G. P. CO6I [MAD-22617] 91
MIRAJ ( S.
B.
SHINTRE )
android:gravity="center"
android:text="7"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="8"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="9"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
</TableRow>
G. P. CO6I [MAD-22617] 92
MIRAJ ( S.
B.
SHINTRE )
<TableRow android:layout_marginTop="25dp">
<TextView
android:layout_width="wrap_conte"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="*"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="0"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
G. P. CO6I [MAD-22617] 93
MIRAJ ( S.
B.
SHINTRE )
android:layout_weight="1"
android:gravity="center"
android:text="#"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />
</TableRow>
<TableRow android:layout_marginTop="25dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="25dp" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_weight="1"
app:srcCompat="@drawable/call" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
G. P. CO6I [MAD-22617] 94
MIRAJ ( S.
B.
SHINTRE )
android:layout_weight="1"
android:gravity="center" />
</TableRow>
</TableLayout>
Output:
G. P. CO6I [MAD-22617] 95
MIRAJ ( S.
B.
SHINTRE )
5. Relative Layout:
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/picture"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textStyle="bold"
android:textColor="#FFEB3B"
android:text="OHA"
android:textSize="20sp"
android:backgroundTint="#E91E63"
android:id="@+id/b1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
G. P. CO6I [MAD-22617] 96
MIRAJ ( S.
B.
SHINTRE )
android:layout_centerInParent="true"
android:layout_marginRight="55dp"
android:layout_toLeftOf="@+id/b1"
android:backgroundTint="#FFEB3B"
android:text="Chip makers"
android:textColor="#E91E63"
android:textStyle="bold" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
android:layout_marginRight="13dp"
android:layout_marginBottom="335dp"
android:backgroundTint="#FFEB3B"
android:text="Software Companies"
android:textColor="#E91E63"
android:textStyle="bold" />
<Button
android:layout_width="wrap_content
android:layout_height="wrap_content
android:layout_alignParentTop="true
android:layout_centerInParent="true"
G. P. CO6I [MAD-22617] 97
MIRAJ ( S.
B.
SHINTRE )
android:backgroundTint="#FFEB3B"
android:text="Handset Manufacturer"
android:layout_marginTop="180dp"
android:textColor="#E91E63"
android:textStyle="bold" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="180dp"
android:backgroundTint="#FFEB3B"
android:layout_centerInParent="true"
android:text="Commercialization companies"
android:textColor="#E91E63"
android:textStyle="bold" />
</RelativeLayout>
Output:
G. P. CO6I [MAD-22617] 98
MIRAJ ( S.
B.
SHINTRE )
HANDSET MANUFACTURER
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFEB3B"
tools:context=".MainActivity">
<TextView
android:layout_width="315dp"
android:layout_height="42dp"
android:layout_marginTop="30sp"
android:text=" SUBJECT:MAD"
android:textColor="#E71919"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="64dp"
android:layout_marginTop="80dp"
android:textColor="#000000"
android:textSize="20sp" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50sp"
android:layout_marginStart="30dp"
android:layout_marginTop="200dp"
android:text="November 2005"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="October 2005"
android:layout_marginLeft="50dp"
android:layout_marginStart="30dp"
android:layout_marginTop="300dp"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="November 2007"
android:layout_marginStart="250dp"
android:layout_marginTop="200dp"
android:layout_marginLeft="250dp"
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="August 2007"
android:layout_marginLeft="250dp"
android:layout_marginStart="250dp"
android:layout_marginTop="300dp"
/>
<Button
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="280dp"
android:layout_marginStart="260dp"
android:layout_marginTop="400dp"
android:background="#8CECDE"
android:text="Next"
android:textColor="#E71919"
android:textSize="16sp"
/>
<Button
android:layout_height="wrap_conte
nt"
android:layout_marginTop="400dp"
android:background="#8CECDE"
android:text="previous"
android:textColor="#E71919"
android:textSize="16sp"
/>
<Button
android:layout_width="15
3dp"
android:layout_height="wrap_conte
nt"android:layout_gravity="center"
android:layout_marginTop="200dp"
android:background="#82E70C"
android:text="SUBMIT TEST"
android:textSize="20sp"
/>
</FrameLayout>
Output:
G. P. 103
CO6I [MAD-22617]
MIRAJ ( S.
B.
SHINTRE )
SUBJECT:MAD
November
November 2005
2007
Syllabus :
4.2 List View; Grid View; Image View; Scroll View; Custom
Toast Alert.
2] A view occupies a rectangular area on the screen and is responsible for drawing and event
handling.
3] View is base class for widgets which are used to create UI Components ( Buttons, TextField etc. )
4] The ViewGroup subclass is the base class for layouts which are invisible containers that hold other
5] A ViewGroup is a special view that can contain other views (called children) .
6] The view is the component which Android provides us to design the layouts of the app
7] View is also known as widget in android. Any visual(that we can see on screen)and interactive
VIEW HIERARCHY :
the answer is we can set it manually by specifying exact size(with proper units) or by using some
pre-defined values
a] match_parent
B] wrap_content
<ViewName
Attribute1=Value1
Attribute2=Value2
Attribute3=Value3
AttributeN=ValueN
/>
Italways start with anangle bracket, followed by the View name.Wewill introduce youtovarious
types of Views very soon.
Then we write attributes that will define how that view will look on the screen of the application
along with avalue for the attribute. Each view has its ownattributes which we will discuss in the
next few tutorials which will cover various typs of views.
There are two attributes that are necessary for every View. These
are: android:layout_height and android:layout_width.
These attributes define the size of the invisible rectangle that a view makes. Using these attributes
we can easily control the size for every view in our android application.
To create/define a View or a ViewGroup in your android application, there are two possible ways:
myButton.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
myLayout.addView(myButton);
So addView() is the function used to add any View to the UI and setLayoutParams() function is used
to set the various attributes.
The Declarative Approach: In this we define the View and ViewGroups directly in the design XML
files, like we will be doing in the next couple of tutorials where we will study about various
commonly used views.
RadioButton
CheckBox ie
IB
ImageButton
MW
Button
ENTER ie
1] id :
Supply an identifier name of this view, to later retrive it with view. findViewById() or
Activity.findViewById()
Syntax :
android : id = ”@+id/b1” .
2] autoLink :
This attribute is used to control wether the url, phone number are automatically found and
converted to clickable links.
Syntax :
3] alpha :
This property of view has value between 0 (Entirely transparent) and 1 (Completely Opaque).
4] gravity :
The gravity attribute is an optional attribute which is used to control the alignment of the text like
Left, Right, Center, Top, Bottom, Center_Vertical, Center_Horizontal.
Syntax :
5] text :
Syntax :
6] textColor :
The attribute is used to set the text Color in textview. Color values are of form “#argb”, “#rgb”
,”#rrggbb” or “#aarrggbb” .
Syntax :
7] textSize :
The attribute is used to set the size of the text in textview. We can set the size sp(Scale
independent Pixel) , dp(Density Pixel) or px(pixels) .
Syntax :
8] textStyle :
The attribute is used to set the textview. The possible text styles are Bold, Italic andnormal. If we
need to use two or more styles for textview then “ | ” operator is used.
Syntax :
9] background :
The background attribute is used to set the background of a textview . we can set the color or a
drawable in the background of a component or view.
10] padding :
Example:
XML Code:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="30dp"
android:autoLink="web"
android:text="www.google.com"
android:textSize="40sp"
android:background="#673AB7"
/>
<TextView
android:id="@+id/ph_no"
android:layout_width="198dp"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="100dp"
android:autoLink="phone"
android:alpha="1"
android:gravity="center"
android:text="8830288770"
android:textSize="30sp"
android:textColor="#F44336"
android:textStyle="bold|italic"
android:padding="10dp"
/>
<TextView
Output:
A Edit Text is an overly over textview that configures itself to be editable. It is the predefined
subclass of textview that includes rich editing capabilities.
Attributes :
1] id :
Syntax :
android : id = “@+id/idnm”
2] text :
The text attribute is used to set the text (Statically) in edit text. We can set it from .xml or .java file
.
Syntax :
3] hint :
It is an attribute used to set the hint i.e when we want the user to enter in edit text, Whenever
user starts to type in edit text the hint will automatically disappear.
Syntax :
4] gravity :
The gravity attribute is an optional attribute which is used to control the alignment of the text like
Left, Right, Center, Top, Bottom, Center_Vertical, Center_Horizontal.
Syntax :
5] textSize :
The attribute is used toset the size of the font in textview. We can set the size sp(Scale
independent Pixel) , dp(Density Pixel) or px(pixels) .
Syntax :
6] inputType :
The attribute specifies the input type of data/info i.e user going to enter, input type maybe
password, email, phone etc.
Syntax :
7] textColor :
The attribute is used to set the text Color in textview. Color values are of form “#argb”, “#rgb”
,”#rrggbb” or “#aarrggbb” .
Syntax :
8] padding :
The attribute is used to set the padding from Left, Right, Top and Bottom.
9] textStyle :
The attribute is used to set the textview. The possible text styles are Bold, Italic andnormal. If we
need to use two or more styles for EditText then “ | ” operator is used.
10] background :
Thebackground attribute is used to set the background of a EditText. we can set the color ora
drawable in the background of a component or view.
11] alpha :
This property of view has value between 0 (Entirely transparent) and 1 (Completely Opaque).
Xml code:
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="@color/purple_200">
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="@+id/t1"
android:hint="Email"
android:layout_marginTop="50dp"
android:layout_marginLeft="30dp"
android:gravity="left"
android:textStyle="bold"
android:textColor="@color/black"
android:textSize="20sp"
android:inputType="textEmailAddress"
android:fontFamily="sans-serif-condensed"
android:background="@color/teal_200"
android:alpha="1"/>
<EditTextandroid:layout_width="30
0dp"
android:layout_height="wrap_content"
android:id="@+id/t2"
android:hint="Password"
android:layout_marginTop="50dp"
android:layout_marginLeft="30dp"
android:gravity="left"
android:textStyle="bold"
android:textColor="@color/black"
android:textSize="20sp"
android:inputType="textPassword"
android:padding="10dp"
android:background="@color/teal_200"
android:alpha="1"
android:fontFamily="sans-serif-
condensed"/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="@+id/number"
android:hint="Phone Number"
android:drawablePadding="12dp"
android:layout_marginLeft="30dp"
android:gravity="left"
android:textStyle="bold"
android:textColor="@color/black"
android:textSize="20sp"
android:inputType="number"
android:padding="10dp"
android:background="@color/teal_200"
android:alpha="1"
android:fontFamily="sans-serif-
condensed"/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="@+id/dob"
android:hint="Date of birth"
android:layout_marginTop="50dp"
android:drawablePadding="12dp"
android:layout_marginLeft="30dp"
android:gravity="left"
android:textStyle="bold"
android:textColor="@color/black"
android:inputType="datetime"
android:padding="10dp"
android:background="@color/teal_200"
android:alpha="1"
android:fontFamily="sans-serif-condensed"
/>
</LinearLayout>
Output:
Different types of buttons are used in Android such as ImageButton, ToggleButton, RadioButton
and CompoundButton.
Button is asubclass of textview class on button we can perform different actions orevents like,
ClickEvent, PressedEvent, TouchEvent etc.
Attributes :
1] onClick :
This attribute is used to specify the action that should be performed on click of that button, The
value of onclick is a method that should be written in the java file.
2] drawable :
These are drawable resources that are to be drawn on specified alignment of text.
Syntax :
3] android:visibility :
This attribute require Boolean value if it is true then this element is visible in activity otherwise
false.
android:visibility=””
4] android: id
android :id=“@+id/name”
The gravity attributes is an optional attributes which is used to control alignment of the text like
left, right, center, top, bottom, center vertical, center horizontal etc.
6] android:Text
text attributes is used to set the text in a button. We can the text in xml as well as java class.
7] android:TextColor
The text color attributes is used to set color of a button. Color value is in the form of “#rgb”,
“#argb”, “rrggbb”.
9] android:TextSize:
10] android:TextStyle
11] android:Padding:
Xml Code:
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="@+id/btn1"
android:layout_marginLeft="50dp"
android:text="Hello"
android:textSize="30sp"
android:textColor="@color/cardview_light_background"
android:textStyle="bold"
android:textAllCaps="false"
android:backgroundTint="@color/teal_200"
android:tooltipText="This is Button"
android:onClick="click"
android:layout_gravity="center"
/>
</LinearLayout>
In Android , ImageButton is used to display a normal Button with a custom image on the Button,
in simple words you can say imagebutton is abutton with animage that can be pressed or clicked
by the user.
By default, it looks like anormal button with standard button background that changes the color
during different button states.
Attributes :
1] android:src :
Src is an attribute used to set the source of image or we can say image in the ImageButton, to
make layout lookattractive , before using src the image should be saved in the drawable file.
Syntax :
2] android:padding:
Padding attribute is used to set the padding from Left, Right, Top or Bottom of the ImageButton.
iii) padding_top : set padding from top side of the image button.
iv) padding_bottom : set padding from bottom side of the image button.
v) padding : set the padding from all the sides of the image button.
3] android:scaleType:
Controls how the image should be resized or moved to match the size of this ImageView.
Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its
drawable.
5] android:alpha
This property of view has value between 0 (Entirely transparent) and 1 (Completely Opaque).
6] android:clickable
7] android:baseline
8] android:baselineAlignBottom
If true, the image view will be baseline aligned with based on its bottom edge.
9] android:cropToPadding
10] android:onClick
This is the name of the method in this View's context to invoke when the view is clicked.
Example:
Xml Code:
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="300dp"
android:background="@drawable/doremon"
android:id="@+id/b1"
android:scaleType="centerCrop"
android:onClick="click1"
/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="300dp"
android:background="@drawable/nobita"
android:id="@+id/b2"
android:scaleType="centerCrop"
android:onClick="click2"
/>
</LinearLayout>
package com.com.code.imagebutton;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
ImageButton b1,b2;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.b1);
b2=findViewById(R.id.b2);
Toast.makeText(this,"Doremon",Toast.LENGTH_LONG).show();
Toast.makeText(this,"Nobita",Toast.LENGTH_LONG).show();
Output:
Toggle Button isbasically an ON/OFF Button with a light indicator,Which indicatesthe current
state of ToggleButton.
The most simple example of Toggle Button is doing ON/OFF in Sound, Bluetooth, WiFi, HotSpot.
Attributes :
1] checked:
This attribute is used to set the current state of the ToggleButton, The value should be true or
false where Trueshows“CHECKED” state and False shows“UNCHECKED” state of ToggleButton.
Syntax :
android : Checked=”true”.
Attributes :
1] android:disabledAlpha
2] textON / textOFF :
TextOn attribute is used to set the textwhen ToggleButton is in Checked/On state, Wecan set the
textOn in xml as well as java class
Syntax :
3] android:hint
Text to display.
5] android:textAllCaps
6] android:textColor
Text color.
7] android:onClick
This is the name of the method in this View's context to invoke when the view is clicked.
8] android:tootipText:
A tooltip is a small descriptive message that appears near a view when users long press the view or
hover their mouse over it.
9] android:padding
10] android:textAlignment
Example:
Xml Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" tools:context=".MainActivity"
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/t1"
android:textOn="ON"
android:textOff="OFF"
android:layout_marginTop="200dp"
android:layout_marginLeft="100dp"
android:background="@color/purple_200"/>
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/t2"
android:textOff="OFF"
android:layout_marginTop="200dp"
android:layout_marginLeft="50dp"
android:background="#FFF7AC"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onclickMethod"
android:id="@+id/b1"
android:text="SUBMIT."
android:background="#EF85A9"
android:layout_marginLeft="170dp"
android:layout_marginTop="200px"
/>
</LinearLayout>
Java Code:
package com.example.sample2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ToggleButton;
ToggleButton t1,t2;
Button b1;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = findViewById(R.id.t1);
t2 = findViewById(R.id.t2);
b1 =findViewById(R.id.b1);
Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
Output:
In RadioGroup , checking the radioButton out of several radiobuttons added in, it will
automatically uncheck all the others.
It means at one time we can check only one radiobutton from a group of radiobuttons which
belongs to same radiogroup.
Once , RadioButton is checked by user it cannot be unchecked by simply pressing on the same
button. It will automatically uncheck when we press any other RadioButton in the same
RadioGroup
Attributes :
1] android:checked :
This attribute is used to set the current state of the RadioButton, we can set it either True or
False. True shows Checked state and False shows Unchecked state.
Syntax :
2] text :
The attribute is used to set the text in RadioButton. We can set text in xml as well as Java class.
2] android:textColor :
The attribute is used to set the text Color in textview. Color values are of form “#argb”, “#rgb”
,”#rrggbb” or “#aarrggbb” .
Syntax :
3] android:textSize :
Syntax :
4] android:textStyle :
The attribute is used to set the textview. The possible text styles are Bold, Italic and normal. If we
need to use two or more styles for textview then “ | ” operator is used.
Syntax :
5] android:background :
Thebackground attribute is used to set the background of a RadioButton. we can set the color or
a drawable in the background of a component or view.
6] android:padding :
The attribute is used to set the padding from Left, Right, Top and Bottom.
7] android:button
Drawable used for the button graphic (for example, checkbox and radio button).
Example:
Xml Code:
<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:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/rg1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="100dp"
android:textSize="25dp"
android:text="Mango"
android:textColor="#FF9800"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_marginLeft="100dp"
android:textSize="25dp"
android:text="Apple"
android:textColor="#FF2323"/>
<Button
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:text="Show Selected!"
android:layout_marginLeft="100dp"
android:id="@+id/b1"
android:onClick="onclickbuttonMethod"
/>
</RadioGroup>
</LinearLayout>
Java Code:
package com.com.code.radiobutton;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
Button b1;
RadioButton rb1;
RadioGroup rgb;
@Override
setContentView(R.layout.activity_main);
rgb = findViewById(R.id.rg1);
rb1 = findViewById(sid);
if(sid == -1)
Toast.makeText(this,"NOTHING SELECTED",Toast.LENGTH_LONG).show();
else
Toast.makeText(this,rb1.getText(), Toast.LENGTH_LONG).show();
Output:
O Apple
O Apple
Attributes :
1] android:onClick
This is the name of the method in this View's context to invoke when the view is clicked.
2] android:autoText
If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.
3] android:drawableBottom
This is the drawable to be drawn below the text.
4] android:drawableRight
This is the drawable to be drawn to the right of the text.
5] android:editable
If set, specifies that this TextView has an input method.
6] android:text
This is the Text to display.
7] android:background
This is a drawable to use as the background.
8] android:contentDescription
9] android:id
This supplies an identifier name for this view.
10] android:visibility
This controls the initial visibility of the view.
Example:
<CheckBox
android:id="@+id/c1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40dp"
android:layout_y="150dp" />
<CheckBox
android:id="@+id/c2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40dp"
android:layout_y="250dp" />
<CheckBox
android:id="@+id/c3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="40dp"
android:layout_y="350dp" />
<TextView
android:layout_width="214dp"
android:layout_height="39dp"
android:layout_x="121dp"
android:layout_y="150dp"
android:text="Complete MAD assignment" />
<TextView
android:id="@+id/textView"
android:layout_width="214dp"
android:layout_height="39dp"
android:layout_x="121dp"
android:layout_y="250dp"
android:text="Complete python manual" />
<TextView
android:id="@+id/textView2"
android:layout_width="214dp"
android:layout_height="39dp"
android:layout_x="121dp"
android:layout_y="350dp"
android:text="php experiments" />
<TextView
android:id="@+id/textView3"
android:layout_width="214dp"
android:layout_height="39dp"
android:layout_x="121dp"
android:layout_y="450dp"
android:text="EDE complete 12,13 practicals" />
<Button
android:layout_width="103dp"
android:layout_height="39dp"
android:layout_x="139dp"
</AbsoluteLayout>
Java Code:
package com.example.checkbox;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
CheckBox c1,c2,c3,c4;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Output:
ex. When we are uploading or downloading something from the internet, it is better to show the
progress of download/upload to theuser.
In Android, there is a class called ProgressBar that allows properties like below.
Attributes:
1] max :
This attribute is used in Android todefine maximum value of the progress can take.It mustbean
integer value like 100,200 etc.
Syntax :
2] progress :
Syntax :
<ProgressBar
3] progressDrawable :
4] indeterminate :
The indeterminate attribute is used in android to enable the indeterminate mode. In this mode
the progressBar shows a cyclic animation without an indication of progress.
This mode is used in android applications when we don’t know the amount of work to be done.
Example:
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:text="Download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Java code:
package com.example.progressdialog;
import androidx.appcompat.app.AppCompatActivit
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
Button button;
ProgressDialog progressDoalog;
@Overrideprotected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mai
n);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressDoalog.setMax(100);
progressDoalog.setTitle("ProgressDialog example");
progressDoalog.show();
newThread(new Runnable() {
@Override
try {
.getMax()) {
Thread.sleep(200);
handle.sendMessage(handle.obtainMessage());
if (progressDoalog.getProgress() == progressDoalog
.getMax()) {
progressDoalog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}).start();
@Override
super.handleMessage(msg);
};
});
Output:
ListView Dispalys a vertically scrollable collection of views, where each view is positioned
immediately below the previous view in the list.
A ViewGroup that creates and managesavertical list of views display themas rows within the list.
Simple ListView display to the string value of each object in an array, use a textview for 11cm.
Android ListView is aview that groups several items anddisplay them in vertical scrollable list.The
list items are automatically inserted to the list using an adapter that pulls content from a source
such as an array or database.
Attributes :
1] divider :
Ex:
<ListView
android : id = “@+id/l1”
android : layout_height = ”match_parent”
android : layout_width = “match-parent”
android : divider = “#f00”
android : divider_height = “1dp” />
2] dividerHeight :
This specifiesthe height of the divider between list items.This could be in dp(Density pixel), sp(Scale
Independent Pixel) or px(pixel).
3] listSelector :
The listSelector property is used to set the selector of the list view. It is generally of orange or sky blue
color mostly. But we can also define our custom color on image as a list selector as per our design.
Syntax :
android : listSelector = “#342”
Example:
</LinearLayout>
<resources>
<string name="app_name">Listview</string>
<string-array name="Cartoon">
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
<item>Doremon</item>
</string-array>
</resources>
Java code:
Package com.example.listview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
String s[]=getResources().getStringArray(R.array.Cartoon);
ArrayAdapter a=new ArrayAdapter(this, android.R.layout.simple_selectable_list_item,s);
l1.setAdapter(a);
}
}
Output:
It holds the data and sends the data to adapterView then view can take the data from the
adapterview and show the data on different views like listView, gridView, Spinner.
ListViewis the subclassof AdapterView and it can be populated bybinding anadapter, which
retrives the data from an external source and creates aview that represents each data entry.
In android commonly used adapters are array adapter and base adapter.
ARRAY ADAPTER :
1] Whenever we have list of single items, which is blocked byanarray.Wecan use ArrayAdapter.
For instance , list of phone contacts, countries or names.
2] By default, ArrayAdapter expects a layout with a single textview if we want to use more
complex view means more customisation in list items, please avoid array adapter and use custom
adapter.
BASE ADAPTER :
1] Base Adapter can be extended to create custom Adapter for displaying a custom list item.
ArrayAdapter is also an implementation of BaseAdapter.
Example:
<ListView
android:id="@+id/l1"
android:layout_width="match_parent"
</LinearLayout>
Java code:
package com.example.prac14;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
setContentView(R.layout.activity_main);
l1=findViewById(R.id.l1);
ArrayAdapter<String> arrayAdapter=new
ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,sub);
l1.setAdapter(arrayAdapter);
l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),""+sub[position],Toast.LENGTH_SHORT).show();
}
});
}
}
GridView will fill the entire screen. It displays data in Grid-Form. Although we use the term data
here, cotent of GridView can be text,images and so on.
Ex. Our default Gallery where umber of images are displayed in GridView.
Attributes:
1] android:id
This is the ID which uniquely identifies the layout.
2] android:columnWidth
This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm.
3] android:gravity
Specifies the gravity within each cell. Possible values are top, bottom, left, right, center,
center_vertical, center_horizontal etc.
4] android:horizontalSpacing
Defines the default horizontal spacing between columns. This could be in px, dp, sp, in, or
mm.
5] android:numColumns
Defines how many columns to show. May be an integer value, such as "100" or auto_fit
which means display as many columns as possible to fill the available space.
6] android:stretchMode
Defines how columns should stretch to fill the available empty space, if any. This must be
either of the values −
• none − Stretching is disabled.
• spacingWidth − The spacing between each column is stretched.
7] android:verticalSpacing
Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or mm.
Example:
Java Code:
package com.example.gridbuttons;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getApplicationContext(),((TextView) view).getText(), Toast.LENGTH_LONG).show();
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
menu/activity_main.xml file:
</menu>
Output:
13 14
1] id:
id is an attribute used to uniquely identify a image view in android.
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.
3] background:
background attribute is used to set the background of a ImageView. We can set acolor ora
drawable in the background of a ImageView.
4] padding:
padding attribute is used to set the padding from left, right, top or bottom of the Imageview.
5] scaleType:
scaleType is an attribute used to control how the image should be re-sized ormoved tomatch the
size of this image view. The value for scale type attribute can be fit_xy, center_crop, fitStart etc.
<TextView
android:layout_width="wrap_content"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/rabbit"
android:id="@+id/img1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Change Image"
android:id="@+id/b1"
/>
</LinearLayout>
Java file:
package com.example.myapplication4;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
Button b;
ImageView i1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton(){
b=(Button)findViewById(R.id.b1);
i1=(ImageView)findViewById(R.id.img1);
b.setOnClickListener(new OnClickListener() {
@Override
i1.setImageResource(R.drawable.india);
}
});
}
}
Output:
ScrollView may have only one direct child placed within it.
ScrollView supports vertical scrolling only for horizontal scrolling use horizontal ScrollView.
A ScrollView is a FrameLayout which puts onechild in it containing the whle contents to scroll,
This child may itself be a layout manager within a composite hierarchy of an object.
Attributes:
1] android:onClick:
Name of the method in this View’s context to invoke when the view is clicked.
2] android: scrollbars:
In android, scrollbars attribute is used to show the scrollbars in horizontal or vertical direction. The possible
Value of scrollbars is vertical, horizontal or none. By default scrollbars is shown in vertical direction in
scrollView and in horizontal direction in HorizontalScrollView.
3] android:fillViewport:
Defines whether the scrollview should stretch its content to fill the viewport.
4] android:padding:
Sets the padding, in pixels, of all four edges.
5] Android: alpha:
alpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque).
6] android:background :
A drawable to use as the background
7] android:clickable:
Defines whether this view reacts to click events
8] android:contentDescription:
Defines text that briefly describes content of the view
9] android:id
Supplyan identifier namefor this view, tolater retrieve it with View.findViewById() or
Activity.findViewById().
10] android:isScrollContainer
Set this if theviewwill serve as ascrolling container, meaningthat it canberesized to shrink itsoverall
window so that there will be space for an input method.
11] android:minHeight :
12] android:minWidth:
Defines the minimum width of the view.
Example:
<TextView
android:id="@+id/textView"
android:layout_width="185dp"
android:layout_height="51dp"
android:layout_gravity="center_horizontal"
android:text="Contacts"
android:layout_marginLeft="150sp"
android:layout_marginStart="150sp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#F9A825"
android:textSize="30sp" />
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="John stephan 9876543770"
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Alisa Khan 9876743210"
android:textColor="#FAFAFA"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="John stephan2 9876543770"
android:textColor="#FAFAFA"
android:layout_marginTop="50dp"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Andrew Son2 9996543210"
android:textColor="#FAFAFA"
android:layout_marginTop="50dp"
android:textSize="30sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Diana Penty2 9874443210"
android:textColor="#FAFAFA"
android:textSize="30sp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Output:
2. show():
This method is used to display the Toast on the screen. This method is display the text which we create using
makeText() method ofToast.
3. setGravity(int,int,int):
This method is used to set the gravity for the Toast. This method accepts three parameters:
a Gravity constant, an x-position offset, and a y-position offset.
4. setText(CharSequence s):
This methodis usedto set the text for theToast. If we use makeText() method and then we want to change
the text value for the Toast then we use this method.
5. nsetText(CharSequence s):
This methodis usedto set the text for theToast. If we use makeText() method and then we want to change
the text value for the Toast then we use this method.
6. setDuration(int duration):
This method is usedto set the durationfor the Toast. If we use makeText() method and then we want to
change the duration for the Toast then we use this method.
7. inflate(int, ViewGroup):
This method is used toinflate the layout from thexml. Inthis method first parameter is the layout resource
ID and the second is the root View.
8. setView(View):
Example:
<FrameLayout 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:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="#8C6562">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" android:text="Score :
/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Question : 1/5"
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="210dp"
android:text="00:16"
android:textColor="#000000"
android:textSize="60dp"
android:layout_marginTop="10dp"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What is 2+2?"
android:layout_gravity="center|top"
android:layout_marginTop="200dp"
android:textSize="25dp"
<RadioButton
android:id="@+id/r1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:textColor="#000000"
android:textSize="20dp"
android:layout_marginTop="250dp"/>
<RadioButton
android:id="@+id/r2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6"
android:textColor="#000000"
android:textSize="20dp"
android:layout_marginTop="300dp"/>
<RadioButton
android:id="@+id/r3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="20dp"
android:layout_marginTop="350dp"/>
</FrameLayout>
Java code:
package com.example.framelayout1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
RadioButton r1,r2,r3;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
addListenerOnButton();
r1=findViewById(R.id.r1);
r2=findViewById(R.id.r2);
r3=findViewById(R.id.r3);
r1.setOnClickListener(new View.OnClickListener() {
@Override
});
r2.setOnClickListener(new View.OnClickListener() {
@Override
});
@Override
});
Output:
Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode. The
time consists of hours, minutes and clock format. Android provides this functionality through
TimePicker class.
Methods :
1. is24HourView()
This method returns true if this is in 24 hour view else false
2. isEnabled()
This method returns the enabled status for this view
3. setCurrentHour(Integer currentHour)
This method sets the current hour
4. setCurrentMinute(Integer currentMinute)
This method sets the current minute
5. setEnabled(boolean enabled)
This method set the enabled state of this view
6. setIs24HourView(Boolean is24HourView)
This method set whether in 24 hour or AM/PM mode
7. setOnTimeChangedListener(TimePicker.OnTimeChangedListener
onTimeChangedListener)
This method Set the callback that indicates the time has been adjusted by the user
Example:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout 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:layout_width="match_parent"
<Button
android:id="@+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:layout_x="8dp"
android:layout_y="469dp"
android:background="#C51162"
android:text="-2hr:15min"
android:textColor="#ffffff" />
<TimePicker
android:id="@+id/tp1"
android:layout_width="match_parent"
android:layout_height="366dp"
android:layout_x="0dp"
android:layout_y="0dp"
android:background="#C0CA33" />
<Button
android:id="@+id/b1"
android:layout_width="122dp"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:layout_x="110dp"
android:layout_y="469dp"
android:background="#C51162"
android:text="Current Time"
android:textColor="#ffffff" />
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:layout_x="250dp"
android:layout_y="472dp"
android:background="#C51162"
android:text="+2:15min"
android:textColor="#ffffff" />
<TextView
android:id="@+id/t1"
</AbsoluteLayout>
Java file:
package com.example.prac161;
import androidx.appcompat.app.AppCompatActivity;
import android.icu.text.TimeZoneFormat;
import android.widget.Toast;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.TimeZone;
b1=findViewById(R.id.b1);
b2=findViewById(R.id.b2);
b3=findViewById(R.id.b3);
t1=findViewById(R.id.t1);
tp1=findViewById(R.id.tp1);
tp1.setIs24HourView(false);
Output:
Methods :
1. getDayOfMonth()
This method gets the selected day of month
2. getMonth()
This method gets the selected month
3. getYear()
This method gets the selected year
4. setMaxDate(long maxDate)
This method sets the maximal date supported by this DatePicker in milliseconds since January
1, 1970 00:00:00 in getDefault() time zone
5. setMinDate(long minDate)
This method sets the minimal date supported by this NumberPicker in milliseconds since
January 1, 1970 00:00:00 in getDefault() time zone
6. setSpinnersShown(boolean shown)
This method sets whether the spinners are shown
8. getCalendarView()
9. getFirstDayOfWeek()
This Method returns first day of the week
Example:
<DatePicker
android:id="@+id/t1"
android:layout_width="340dp"
android:layout_height="wrap_content"
android:layout_x="5dp"
android:layout_y="0dp"
android:background="#FFF9C4" />
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="36dp"
android:layout_marginTop="10sp"
android:layout_x="100dp"
android:layout_y="450dp"
android:background="#EC407A"
android:text="SHOW"
android:textColor="#ffffff" />
</AbsoluteLayout>
Java Code:
package com.example.calender;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.b1);
t1=findViewById(R.id.t1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),day+"\n"+month+"\n"+year,
Toast.LENGTH_SHORT).show();
}
});
}
Output:
WriteaprogramtodesignaSimpleCalculatorusingEditText
.xml file :
<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:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="@drawable/backgroundim">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#A3FFFFFF"
android:orientation="vertical">
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
<ImageView android:id="@+id/imageView"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:layout_marginTop="40dp"
app:srcCompat="@drawable/imgview" />
<EditText android:id="@+id/t1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="30dp"
android:layout_marginRight="50dp"
android:ems="10"
android:inputType="number" />
<EditText android:id="@+id/t2"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginRight="50dp"
android:ems="10" android:hint="Enter
Second Number"
android:inputType="number" />
<EditText android:id="@+id/t3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:clickable="false"
android:editable="false" android:ems="10"
android:focusable="false"
android:hint="Answer" />
<Button android:id="@+id/b1"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_marginLeft="70dp" android:layout_marginTop="30dp"
android:text="ADDITION" />
<Button android:id="@+id/b2"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginLeft="70dp"
android:layout_marginTop="20dp" android:layout_marginRight="70dp"
<Button android:id="@+id/b3"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginLeft="70dp"
android:layout_marginTop="20dp" android:layout_marginRight="70dp"
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:layout_marginTop="20dp"
android:layout_marginRight="70dp"
android:background="@drawable/round"
android:text="DIVISION" />
<Button android:id="@+id/b5"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginLeft="70dp"
android:layout_marginTop="20dp" android:layout_marginRight="70dp"
</LinearLayout>
</ScrollView>
</LinearLayout>
</LinearLayout>
package com.example.utkscalculator;
import androidx.appcompat.app.AppCompatActivity;
android.view.View;
android.widget.Button;
import android.widget.EditText;
t1,t2,t3;
s1,s2; @Override
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.Layout
Params.FLAG_FULLSCREEN);
t1=findViewById(R.id.t1);
t2=findViewById(R.id.t2);
b1=findViewById(R.id.b1);
b2=findViewById(R.id.b2);
b3=findViewById(R.id.b3);
b4=findViewById(R.id.b4);
b5=findViewById(R.id.b5);
a,b,ans;
a=Integer.parseInt(String.valueOf(t1.getText()));
b=Integer.parseInt(String.valueOf(t2.getText())); ans=a+b;
t3.setText("Addition : "+ans);
});
a,b,ans;
a=Integer.parseInt(String.valueOf(t1.getText())); b=Integer.parseInt(String.valueOf(t2.getText()));
"+ans);
});
a,b,ans;
a=Integer.parseInt(String.valueOf(t1.getText()));
b=Integer.parseInt(String.valueOf(t2.getText())); ans=a*b;
t3.setText("Multiplication : "+ans);
});
a,b,ans;
a=Integer.parseInt(String.valueOf(t1.getText()));
b=Integer.parseInt(String.valueOf(t2.getText())); ans=a/b;
t3.setText("Division : "+ans);
a,b,ans;
a=Integer.parseInt(String.valueOf(t1.getText()));
b=Integer.parseInt(String.valueOf(t2.getText())); ans=a%b;
t3.setText("Modulus : "+ans);
});
Answe
20
10a
Multiplication: 200
<AbsoluteLayout 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:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/cake"
tools:context=".MainActivity">
<TextView android:layout_width="410sp"
android:layout_height="102dp"
android:paddingTop="30sp"
android:background="#FBE9E7"
android:textAlignment="center"
android:textStyle="italic"
android:textAppearance="@style/TextAppearance.AppCompat"
android:textColor="#8E24AA"
android:textSize="40sp"
android:layout_x="0sp"
android:layout_y="0sp"
/>
android:layout_width="203dp"
android:layout_height="53dp"
android:layout_marginTop="300sp"
android:layout_x="31dp"
android:layout_y="204dp"
android:textAlignment="center"
android:textColor="#8E24AA"
android:textSize="30sp"
android:textStyle="italic"/>
<TextView android:layout_width="209dp"
android:layout_height="58dp"
android:layout_marginTop="300sp"
android:layout_x="21dp"
android:layout_y="136dp"
android:text="Thank you"
android:textAlignment="center"
android:textColor="#8E24AA"
android:textSize="30sp"
android:textStyle="italic"/>
<TextView
android:layout_height="42dp"
android:layout_marginTop="300sp" android:layout_x="8dp"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat"
android:textColor="#8E24AA"
android:textSize="20sp"
android:textStyle="italic" />
<ImageView android:layout_width="67dp"
android:layout_height="70dp"
android:layout_marginTop="300sp"
android:layout_x="4dp"
android:layout_y="495dp"
android:src="@drawable/calling" />
<ImageView android:layout_width="80dp"
android:layout_height="68dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_y="570dp"
android:src="@drawable/msg_two" />
<ImageView android:layout_width="70dp"
android:layout_height="74dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="350sp"
android:layout_x="5dp"
android:layout_y="651dp"
android:src="@drawable/world" />
<TextView
android:layout_width="167dp"
android:layout_height="50sp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="300sp" android:layout_x="119dp"
android:layout_y="502dp" android:autoLink="phone"
<TextView android:layout_width="214dp"
android:layout_height="50sp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="350sp"
android:layout_x="119dp"
android:layout_y="565dp"
android:autoLink="email"
android:text="[email protected]" android:textColorLink="#8E24AA"/>
<TextView android:layout_width="185dp"
android:layout_height="50sp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="350sp"
android:layout_x="121dp"
android:layout_y="653dp"
android:autoLink="web"
android:text="www.bellbakers.com"
android:textColorLink="#8E24AA" />
</AbsoluteLayout>
<TableLayout 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:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/img"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView android:layout_width="match_parent"
android:layout_height="77dp"
android:text="Student Form"
android:textAlignment="center"
android:textStyle="bold"
android:textColor="#ffffff"
android:fontFamily="monospace"
android:textSize="40sp" />
<TableRow
android:layout_width="350dp"
android:layout_height="70dp">
android:layout_height="65dp"
android:fontFamily="monospace"
android:text=" Name:"
android:textColor="#ffffff"
android:textSize="20sp"
android:textStyle="bold" />
<EditText android:layout_width="180dp"
android:layout_height="65dp"
android:textColor="#ffffff" />
</TableRow>
<TableRow
android:layout_width="120dp"
android:layout_height="70dp">
<TextView android:layout_width="wrap_content"
android:layout_height="65dp"
android:fontFamily="monospace" android:text="
android:textColor="#ffffff"
android:textStyle="bold" />
<EditText android:layout_width="241dp"
android:layout_height="65dp"
android:inputType="phone"
android:layout_marginTop="20sp"
android:textColor="#ffffff" />
</TableRow>
<TableRow
android:layout_width="120dp"
android:layout_height="70dp">
<TextView android:layout_width="wrap_content"
android:layout_height="65dp"
android:fontFamily="monospace" android:text="
android:textColor="#ffffff" android:textSize="20sp"
android:textStyle="bold" />
<EditText
android:layout_height="65dp"
android:layout_marginTop="20sp"
android:textColor="#ffffff" />
</TableRow>
<TableRow
android:layout_width="120dp"
android:layout_height="70dp">
<TextView android:layout_width="wrap_content"
android:layout_height="65dp"
android:fontFamily="monospace" android:text="
Address:" android:layout_marginTop="20sp"
android:textColor="#ffffff" android:textSize="20sp"
android:textStyle="bold" />
<EditText android:layout_width="241dp"
android:layout_height="65dp"
android:layout_marginTop="20sp"
android:textColor="#ffffff" />
</TableRow>
<TableRow android:layout_width="120dp"
<Button android:layout_width="165dp"
android:layout_height="61dp"
android:fontFamily="monospace"
android:text="Submit"
android:textSize="20sp"
android:background="@drawable/round"
android:layout_marginTop="30sp"
android:textStyle="bold" />
<Button android:layout_width="wrap_content"
android:layout_height="65dp"
android:fontFamily="monospace"
android:text="Cancel"
android:background="@drawable/round"
android:layout_marginTop="30sp"
android:textSize="20sp"
android:layout_marginLeft="30sp"
android:layout_marginStart="30sp"
android:layout_marginRight="50sp"
android:layout_marginEnd="50sp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
.xml file
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView android:id="@+id/i1"
android:layout_width="match_parent"
android:layout_height="385dp"
android:src="@drawable/offbulb" />
<ToggleButton android:id="@+id/tb1"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginTop="10sp"
android:layout_marginStart="150sp"
android:layout_marginLeft="150sp" android:text="OFF"
/>
</LinearLayout>
.java file
package com.example.prac91;
android.os.Bundle;
import android.view.View;
import android.widget.Button; import
android.widget.ImageView; import
android.widget.ToggleButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); addListenerOnButton();
}
<ImageButton android:layout_width="731dp"
android:layout_height="51dp"
android:layout_x="5dp" android:layout_y="4dp"
android:background="@drawable/round"
android:src="@drawable/top" />
<TextView android:id="@+id/t1"
android:layout_width="436dp"
android:layout_height="44dp"
android:layout_x="90dp" android:layout_y="97dp"
android:text="Ankita is presenting screen"
android:textAlignment="center"
android:textColor="#ffffff" android:textSize="20sp"
/>
<ImageButton android:id="@+id/b1"
android:layout_width="132dp"
android:layout_height="104dp"
android:layout_x="0dp"
android:layout_y="169dp"
android:background="@drawable/round"
android:onClick="end" android:src="@drawable/end"/>
<ImageButton android:id="@+id/b3"
android:onClick="mic"
android:layout_width="110dp"
android:layout_height="103dp"
android:layout_x="244dp"
android:layout_y="170dp"
android:background="@drawable/round" android:src="@drawable/mic"/>
<ImageButton android:id="@+id/b4"
android:onClick="hand"
android:layout_width="116dp"
android:layout_height="104dp"
android:layout_x="373dp"
android:layout_y="172dp"
android:background="@drawable/round" android:src="@drawable/hand" />
<ImageButton android:onClick="dots"
android:id="@+id/b5"
android:layout_width="128dp"
android:layout_height="113dp"
android:layout_x="506dp"
android:layout_y="165dp"
</AbsoluteLayout>
.java file
package com.example.prac92;
android.os.Bundle;
import android.view.View;
import android.widget.ImageButton; import
android.widget.TextView; import
android.widget.Toast;
<ImageButton
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_y="50dp"
android:layout_x="100dp"
android:src="@drawable/b1"
android:scaleType="centerCrop"
android:onClick="p1"
android:id="@+id/i1"
/>
<ImageButton
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_y="250dp"
android:layout_x="100dp"
android:src="@drawable/b2"
android:scaleType="centerCrop"
android:onClick="b1"
android:id="@+id/i2"
/>
<ImageButton
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_y="450dp"
android:layout_x="100dp"
android:src="@drawable/b3"
android:scaleType="centerCrop"
android:onClick="f1"
</AbsoluteLayout>
Java File
package com.example.myapplication;
android.os.Bundle;
import android.view.View;
importandroid.widget.ImageButton; import
android.widget.Toast;
ImageButton i1,i2,i3;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i1=findViewById(R.id.i1);
i2=findViewById(R.id.i2);
i3=findViewById(R.id.i3);
}
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="50dp"
android:text="What's Your Hobby ?"
android:gravity="center"
android:textStyle="bold"
android:textSize="20dp"
android:textColor="@color/black"
android:fontFamily="serif"
/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/b1"
android:onClick="bg1" android:id="@+id/bt1"
/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/b3"
android:onClick="bg3" android:id="@+id/bt3"
/>
<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="20dp"
android:background="@drawable/b4"
android:onClick="bg4" android:id="@+id/bt4"
/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/b5"
android:onClick="bg5" android:id="@+id/bt5"
/>
android:background="@drawable/b6"
android:onClick="bg6" android:id="@+id/bt6"
/>
</LinearLayout>
</LinearLayout>
Java Code
package com.example.imagebuttonprac4;
android.os.Bundle;
import android.view.View;
import android.widget.Toast;
Output:
<EditText android:layout_width="100dp"
android:layout_height="100dp"
android:background="#E91E63"
android:layout_margin="10dp"
android:id="@+id/t1"
android:gravity="center"
/>
<Button android:layout_width="100dp"
android:layout_height="100dp"
android:text="+"
android:textSize="50dp"
android:layout_margin="10dp"
android:gravity="center"
/>
<EditText android:layout_width="100dp"
android:layout_height="100dp"
android:background="#E91E63"
android:layout_margin="10dp"
android:id="@+id/t2"
android:gravity="center"
<Button android:layout_width="100dp"
android:layout_height="100dp"
android:text="="
android:textSize="50dp"
android:layout_margin="10dp"
android:gravity="center"
android:id="@+id/b1"
android:onClick="add"
/>
<EditText android:layout_width="100dp"
android:layout_height="100dp"
android:background="#E91E63"
android:layout_margin="10dp"
android:id="@+id/t3"
android:gravity="center"
/>
</LinearLayout>
Java Code
package com.example.buttonprac1;
android.os.Bundle;
import android.view.View; import
android.widget.EditText;
import android.widget.ImageButton;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void add(View view) { int
s1,s2,s3;
s1=Integer.parseInt(t1.getText().toString());
s2=Integer.parseInt(t2.getText().toString()); s3=s1+s2;
t3.setText(Integer.toString(s3));
}
}
Output:
<TextView android:layout_width="300dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:id="@+id/t1"
android:gravity="center"
android:text="Choose Background Color :"
android:textSize="20dp"
android:textColor="@color/black"
android:textStyle="bold"
android:fontFamily="casual"
/>
<Button android:layout_width="250dp"
android:layout_height="60dp"
android:text="1) GREEN"
android:textSize="30dp"
android:layout_margin="10dp"
android:gravity="center"
android:textStyle="bold"
android:fontFamily="casual"
android:backgroundTint="#FFC107"
android:onClick="g"
/>
<Button android:layout_width="250dp"
<Button android:layout_width="250dp"
android:layout_height="60dp"
android:text="3) RED"
android:textSize="30dp"
android:layout_margin="10dp"
android:gravity="center"
android:textStyle="bold"
android:fontFamily="casual"
android:backgroundTint="#FFC107"
android:onClick="r"
/>
<Button android:layout_width="250dp"
android:layout_height="60dp"
android:text="4) CYAN"
android:textSize="30dp"
android:layout_margin="10dp"
android:gravity="center"
android:textStyle="bold"
android:fontFamily="casual"
android:backgroundTint="#FFC107"
android:onClick="c"
/>
</LinearLayout>
Java Code
package com.example.buttonprac4;
LinearLayout l1;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1 = (LinearLayout)findViewById(R.id.l1);
}
Output:
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:layout_marginTop="50dp"
android:background="#05BB86FC"
android:layout_marginLeft="10dp"
/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"
/>
</LinearLayout>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="120dp"
/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="40dp"
/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:background="#05BB86FC"
android:layout_marginTop="40dp"
android:layout_marginLeft="20dp"
/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="20dp"
/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:background="#05BB86FC"
android:layout_marginTop="50dp"
android:layout_marginLeft="120dp"
/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O"
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#9C27B0"
android:background="#05BB86FC"
android:layout_marginTop="40dp"
android:layout_marginLeft="10dp"
/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" android:textStyle="bold"
android:textSize="100dp"
android:textColor="#E91E63"
android:background="#05BB86FC"
android:layout_marginTop="40dp"
android:layout_marginLeft="20dp"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Menu card"
android:textSize="50dp"
android:layout_marginTop="30dp"
android:layout_gravity="center_horizontal"
android:textColor="#00BCD4"
android:fontFamily="sans-serif-smallcaps"
/>
</LinearLayout>
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:background="#607D9A">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textStyle="bold"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="20dp"
android:text="Sr no"/>
<TextView
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="1"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Veg Pizza"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
</TableRow>
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="2"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Aloo Tikki Burger"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="75/-"
/>
</TableRow><TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="3"
android:textAlignment="center"/>
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Blue Lagoon"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="90/-"
/>
</TableRow>
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="6"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Cold Coffee"/>
<TextView android:layout_width="wrap_content"
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Cappuccino"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="105/-"
/>
</TableRow>
<TableRow android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="9"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Peri Peri fries"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#BCC7E3E1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="10dp"
android:text="10"
android:textAlignment="center"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-condensed"
android:layout_marginLeft="30dp"
android:text="Cad B"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:fontFamily="sans-serif-smallcaps"
android:layout_marginLeft="25dp"
android:text="120/-"
/>
</TableRow>
</TableLayout>.
<ImageView android:layout_width="wrap_content"
android:layout_height="400dp"
android:src="@drawable/compass"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="147°\nSoutheast"
android:textColor="@color/design_default_color_surface" android:textSize="40sp"
android:textAlignment="center"
android:layout_x="110dp"
android:layout_y="430dp"/>
</AbsoluteLayout>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2:05" android:textSize="60dp"
android:textColor="@color/design_default_color_surface" android:layout_x="10dp"
android:layout_y="10dp"
Code:
<?xml version="1.0" encoding="utf-8"?> xmlns:app="http://schemas.android.co
m/apk/res-auto"
<RelativeLayout
xmlns:android="http://schemas.android.
com/apk/res/android" xmlns:tools="http://schemas.android.co
m/tools"
android:layout_toRightOf="@+id/img1"
android:layout_alignParentLeft="true"
android:layout_marginTop="60dp"
android:layout_alignParentTop="true" android:id="@+id/btn1"
android:layout_marginLeft="4dp" />
android:layout_marginTop="15dp" <Button
android:src="@drawable/pro5" />
android:layout_width="wrap_content"
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Delete"
android:layout_height="wrap_content" android:textSize="20dp"
android:textSize="20dp" android:backgroundTint="#BEBFBF"
android:textColor="#151515"
android:layout_toEndOf="@+id/img1"
android:layout_marginTop="25dp" android:layout_toRightOf="@+id/btn1"
/> android:layout_marginTop="60dp"
<Button android:id="@+id/btn2"
/>
android:layout_width="wrap_content"
<ImageView
android:layout_marginBottom="16dp" android:layout_marginTop="10dp"
android:src="@drawable/pro3" android:id="@+id/bt9"
/> />
<TextView <Button
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="Lilly" android:text="Delete"
android:textSize="20dp" android:textSize="20dp"
android:textStyle="normal"
android:layout_toEndOf="@+id/img2" android:backgroundTint="#BEBFBF"
android:layout_below="@+id/btn7" android:textColor="#151515"
android:layout_marginTop="55dp"
android:id="@+id/text5" android:layout_toRightOf="@+id/bt9"
/> android:layout_below="@+id/text5"
<Button android:layout_marginTop="10dp"
android:id="@+id/btn10"
android:layout_width="wrap_content" />
android:layout_centerInParent="true" android:backgroundTint="#2196F3"
android:textColor="#FFFF"
android:layout_centerHorizontal="true"
android:layout_toRightOf="@+id/img3"
android:layout_marginLeft="4dp"
android:layout_below="@+id/text3"
android:src="@drawable/pro4" />
android:id="@+id/btn5"
<TextView
/>
android:layout_width="wrap_content" <Button
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:text="Dragon"
android:textSize="20dp" android:layout_height="wrap_content"
android:layout_marginLeft="10dp" android:text="Delete"
android:textSize="20dp"
android:layout_toEndOf="@+id/img3"
android:textStyle="normal"
android:layout_below="@+id/btn3"
android:backgroundTint="#BEBFBF"
android:layout_marginTop="50dp"
android:textColor="#151515"
android:id="@+id/text3"
/> android:layout_toRightOf="@+id/btn5"
android:layout_below="@+id/text3"
<Button android:id="@+id/btn6"
/>
android:layout_toRightOf="@+id/img3"
android:layout_centerInParent="true"
android:layout_below="@+id/text2"
android:layout_marginLeft="4dp"
android:id="@+id/btn3"
/>
android:layout_marginBottom="23dp"
android:src="@drawable/pro6" /> <Button
<TextView
android:layout_width="wrap_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_height="wrap_content" android:text="Delete"
android:textSize="20dp"
android:text="Shinchan"
android:textStyle="normal"
android:textSize="20dp"
android:backgroundTint="#BEBFBF"
android:id="@+id/text2"
android:textColor="#151515"
android:layout_toEndOf="@+id/img3"
android:layout_toRightOf="@+id/btn3"
android:layout_marginTop="150dp"
android:layout_below="@+id/text2"
/>
android:id="@+id/btn4"
<Button
/>
android:layout_width="wrap_content"
<ImageView android:id="@+id/img5"
android:layout_height="wrap_content"
<Button
android:layout_width="wrap_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Doremon"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Delete"
android:layout_marginLeft="10dp"
android:textSize="20dp"
android:textStyle="normal"
android:layout_toEndOf="@+id/img5"
android:backgroundTint="#BEBFBF"
android:layout_below="@+id/btn5"
android:textColor="#151515"
android:layout_marginTop="25dp"
android:id="@+id/text4"
android:layout_toRightOf="@+id/btn7"
/>
android:layout_below="@+id/text4"
android:id="@+id/btn8"
<Button />
</RelativeLayout>
android:layout_width="wrap_content"
android:layout_y="100dp"
<?xml version="1.0" encoding="utf-8"?>
android:src="@drawable/sun"/>
<AbsoluteLayout
xmlns:android="http://schemas.android.com/
apk/res/android"
xmlns:app="http://schemas.android.com/apk
/res-auto"
xmlns:tools="http://schemas.android.com/to
ols"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_
background"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="#0E87C4"
android:layout_x="10dp"
android:layout_y="20dp"
android:text="Sangli-Miraj-Kupwad"
android:textSize="35sp"
android:drawablePadding="10dp"/>
<ImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_width="wrap_co android:fontFamily="sans-serif-smallcaps"
ntent"
android:textColor="@color/design_default_color
android:layout_height="wrap_c _surface"
ontent" android:layout_x="310dp"
android:fontFamily="sans-serif- android:layout_y="150dp"
smallcaps" android:text="F"
android:textColor="#FFFFFF" android:textSize="30sp"/>
android:layout_x="190dp"
android:layout_y="100dp"
android:text="37°"
android:textSize="80sp"/>
<TextView
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c
ontent"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="#FFFFFF"
android:layout_x="310dp"
android:layout_y="110dp"
android:text="C"
android:textSize="30sp"/>
<TextView
android:layout_width="wrap_co
ntent"
android:layout_width="wrap_content"
android:textColor="@color/design_default_c
android:layout_height="wrap_content" olor_surface"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="@color/design_default_c
olor_surface"
android:layout_x="100dp"
android:layout_y="200dp"
android:text="Hazy Sunshine"
android:textSize="35sp"/>
<TextView
android:layout_width="370dp"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="@color/design_default_c
olor_surface"
android:layout_x="20dp"
android:layout_y="260dp"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
android:layout_y="350dp" android:textStyle="bold"/>
android:text="Today"
android:textSize="20sp"/> <TextView
android:layout_width="wrap_content"
<ImageView android:layout_height="wrap_content"
android:layout_width="50d android:fontFamily="sans-serif-smallcaps"
p"
android:textColor="@color/design_default_color
android:layout_height="45d _surface"
p" android:layout_x="20dp"
android:layout_y="390dp"
android:src="@drawable/s
un"/>
<TextView
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c
ontent"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="@color/design_default_color
_surface"
android:layout_
x="30dp"
android:layout_
y="450dp"
android:text="3
7°"
android:text="24°"
android:textSize="20sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="@color/design_default_c
olor_surface"
android:layout_x="100dp"
android:layout_y="350dp"
android:text="Tue 27"
android:textSize="20sp"/>
<ImageView
android:layout_width="50dp"
android:layout_height="45dp"
android:layout_x="100dp"
android:layout_y="390dp"
android:src="@drawable/sun"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
smallcaps"
x="110dp" smallcaps"
android:layout_
android:textColor="@color/design_default_color
y="450dp" _surface"
android:text="3 android:layout_x="180dp"
9°" android:layout_y="350dp"
android:textSty
le="bold"/> <ImageView
android:layout_width="50dp"
<TextView android:layout_height="45dp"
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c
ontent"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="@color/design_default_color
_surface"
android:layout_x="110dp"
android:layout_y="490dp"
android:text="24°"
android:textSize="20sp"/>
<TextView
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c
android:layout_y="390dp" android:layout_height="wrap_content"
android:src="@drawable/sun"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="@color/design_default_c
olor_surface"
android:layout_x="190dp"
android:layout_y="450dp"
android:text="39°"
android:textSize="20sp"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-
smallcaps"
android:textColor="@color/design_default_c
olor_surface"
android:layout_x="190dp"
android:layout_y="490dp"
android:text="25°"
android:textSize="20sp"/>
android:textColor="@color/design_default_color android:textColor="@color/design_default_color
_surface" _surface"
android:layout_x="26 android:layout_x="270dp"
0dp" android:layout_y="450dp"
android:layout_y="35 android:text="40°"
0dp" android:textSize="20sp"
android:text="Thu android:textStyle="bold"/>
29"
android:textSize="20 <TextView
sp"/> android:layout_width="wrap_content"
android:layout_height="wrap_content"
<ImageView android:fontFamily="sans-serif-smallcaps"
android:layout_width
="50dp"
android:layout_heigh
t="45dp"
android:layout_x="26
0dp"
android:layout_y="39
0dp"
android:src="@draw
able/sun"/>
<TextView
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c
ontent"
android:text="26°"
android:textSize="20sp"/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_x="340dp"
android:layout_y="410dp"
android:rotation="270"
android:src="@android:drawable/arrow_dow
n_float"
app:tint="#FFFEFA"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="530dp"
android:backgroundTint="#23F4EEEE"
android:padding="10dp"
android:text="Daily Summary"
app:cornerRadius="10dp" />
<Button
android:layout_width="wrap_content"
3F4EEEE"
android:padding="10dp"
android:text="Hourly"
app:cornerRadius="10dp" />
<Button
android:layout_width="wrap_
content"
android:layout_height="wrap
_content"
android:layout_x="265dp"
android:layout_y="530dp"
android:backgroundTint="#2
3F4EEEE"
android:padding="10dp"
android:text="Details"
app:cornerRadius="10dp" />
</AbsoluteLayout>
Explicit Intent:
Explicit Intents are used to connect the application internally.
ExplicitIntentworkinternallywithinanapplicationto performnavigationanddata transfer.
Example-
Intent intent = new Intent(getApplicationContext(), SecondActivity.class); startActivity(intent);
Intent Filter:
-decide the behavior of an intent.
-Intentaboutthenavigation ofoneactivitytoanother,thatcanbeachieveby declaring
intent filter.
-We can declare an Intent Filter for an Activity in manifest file.
- IntentfiltersspecifythetypeofintentsthatanActivity,serviceorBroadcastreceivercanrespond to.
Activity Lifecycle:
Activityis ascreen thatuserinteractwith. Every Activityinandroidhaslifecycle like created,
started, resumed, paused, stopped or destroyed. These different states are known as Activity
Lifecycle.
onCreate() – Called when the activity is first created
onStart()– Calledjustafterit’screationorbyrestartmethodafteronStop().Here Activity
start becoming visible to user
Diagram:
Content Provider:
Content Provider will act as a central repository to store the applications data in one place and
make that data available for different applications to access whenever it’srequired.
theContentProviderisapartofanandroidapplicationanditwillactasmorelike relational
database to store the app data. We can perform a multiple operations like insert, update, delete and
edit on the data stored in content provider
using insert(), update(), delete() and query() methods.
contentproviderishaving differentwaystostoreapp data.Theapp datacanbestoredin aSQLite
databaseor in files or even over anetworkbased onourrequirements. By using content providers wecan
managedatasuchasaudio,video,imagesandpersonalcontactinformation.
• Content URIs:
To query a content provider, you specify the query string in the form of a URI which has following
format −content://authority/path
content:// - The string content:// is always present in the URI
authority - It represents the name of content provider
path - It represents the table’s path.
The ContentResolver objectusetheURI’s authority to findthe appropriate provider and send the
query objects to the correct provider. After that ContentProvider uses the path of content URI to
choose the right table to access.
Methods:
1. query()-Itreceives arequestfromtheclient.Byusingargumentsitwillgetadata from
requested table and return the data as a Cursor object.
2. insert() - This method will insert a new row into our content provider and it will return the
content URI for newly inserted row.
3. update()-This methodwillupdateanexistingrowsinour contentproviderandit return the
number of rows updated.
4. delete()- Thismethodwilldeletetherowsinourcontentprovideranditreturnthe number of
rows deleted.
5. getType() - This method will return the MIME type of data to given content URI.
6. onCreate() - This method will initialize our provider. The android system will call this
method immediately after it creates our provider.
Fragment:
Fragmentis a part ofan activity which enable more modular activity design. Itwill not be wrong if we say a
fragment is a kind of sub-activity.
We can combine multiple Fragments in Single Activity to build a multi panel UI and reuse a
Fragment in multiple Activities.
• A fragment has its own layout and its own behaviour with its own life cycle callbacks.
• You can add or remove fragments in anactivity while the activity is running.
• You can combine multiple fragments in a single activity tobuild amulti-pane UI.
• A fragment can be used in multiple activities.
Need of Fragment:
• BeforetheintroductionofFragment’swecanonlyshowasingleActivity on the screen at one given point of
timesowewerenotabletodividethescreenandcontroldifferentpartsseparately.Withthehelpof
Fragment’swecandividethescreensindifferentparts and controls different parts separately.
• Byusing FragmentswecancomprisemultipleFragmentsina singleActivity.Fragments have their
own events, layouts and complete life cycle. It provide flexibility and also removed the limitation
of single Activity on the screen at a time.
Types of Fragment:
• Single frame fragments−Singleframefragmentsareusingforhand holddeviceslike mobiles,here
we can show only one fragment as a view.
• List fragments −fragmentshavingspeciallistviewiscalled as listfragment
• Fragments transaction −Usingwithfragmenttransaction.wecanmoveonefragmentto another fragment
Services:
Androidserviceisacomponentthatisusedtoperformoperationsonthe background
such as playing music, handle network transactions, interacting content providers etc. It
doesn't has any UI (user interface).
The service runs in the background indefinitely even if application is destroyed.
• threedifferent types of services:
1. Foreground- A foreground service performs some operation that is noticeable to the
user.
2. Background- Abackgroundserviceperformsanoperationthatisn'tdirectlynoticed by
the user.
TheonStartCommand()methodwillreturnavaluefromoneofthefollowing constants.
1. START_STICKY
It will restart the service in case if it terminated and the Intent data which is passed
toonStartCommand() methodisNULL. Thisissuitable fortheservicewhicharenotexecuting commands
but running independently and waiting for the job.
Android Architecture:
Androidoperatingsystemisastack ofsoftwarecomponentswhichisroughlydividedinto five
sectionsandfour mainlayersasshownbelowinthearchitecture diagram.
Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This provides a level of
abstraction between the device hardware and it contains all the essential hardware drivers like camera, keypad,
displayetc.Also, thekernel handlesallthethingsthat Linuxisreallygood
Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit,
well known library libc, SQLite database which is a useful repository for storage and sharing of application
data,librariestoplay and record audio andvideo, SSLlibraries responsible for Internet securityetc.
Android Libraries
This category encompasses those Java-based libraries that are specific to Android development. Examples
of libraries in this category include the application framework libraries in addition to those that facilitate user
interface building, graphics drawing and database access. A summary of some key core Android libraries
availabletotheAndroiddeveloperisasfollows−
• android.app− Provides access to the application model and is the cornerstone of all Android
applications.
• android.content − Facilitates content access, publishing and messaging between applications
and application components.
• android.database −UsedtoaccessdatapublishedbycontentprovidersandincludesSQLite database
management classes.
• android.opengl −AJavainterfacetotheOpenGLES3Dgraphics rendering API.
• android.os − Provides applications with access to standard operating system services including
messages, systemservicesandinter-process communication.
• android.text −Used to renderand manipulate text on a device display.
• android.view −Thefundamentalbuildingblocks of applicationuserinterfaces.
• android.widget −Arichcollectionofpre-built user interface components such as buttons, labels, list
views, layout managers, radio buttons etc.
• android.webkit − A set of classes intended to allow web-browsing capabilities to be built into
applications.
HavingcoveredtheJava-basedcorelibrariesintheAndroidruntime,itisnowtimetoturnourattentionto the
C/C++basedlibraries containedinthislayerofthe Android software stack.
Android Runtime
This is the third section of the architecture and available on the second layer from the bottom. This section
provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine
specially designed and optimized for Android.
Application Framework
The Application Framework layer provides many higher-level services to applications in the form of Java
classes. Application developersareallowedtomakeuseoftheseservicesintheir applications.
The Android framework includes the following key services −
• ActivityManager−Controlsallaspectsoftheapplicationlifecycleandactivitystack.
• Content Providers−Allowsapplicationstopublishandsharedata withother applications.
• Resource Manager − Provides access to non-code embedded resources such as strings, color settings
and user interfacelayouts.
• Notifications Manager − Allows applications to display alerts and notifications to the user.
• ViewSystem−Anextensiblesetofviewsusedtocreateapplicationuserinterfaces.
Applications
You will find all the Android application at the top layer. You will write your application to be installed on
thislayeronly.ExamplesofsuchapplicationsareContactsBooks,Browser,Games etc.
Multimedia Framework:
A multimedia framework is a software framework thathandles media on acomputerandthrough anetwork.A
good multimedia framework offers an intuitive API and a modular architecture to easilyadd supportfornew
audio,videoand container formatsand transmissionprotocols. Itis meanttobeusedbyapplications suchas
mediaplayersandaudioorvideoeditors,butcanalso beusedtobuildvideoconferencingapplications, media
convertersandothermultimediatools.
Data is processed among modules automatically, it is unnecessary for app to pass buffers between
connected modules one by one.
In contrast to function libraries, a multimedia framework provides a run time environment for the media
processing. Ideally such an environment provides execution contexts for the media processing blocks
separated from the application using the framework. The separation supports the independent processing of
multimedia data in a timely manner. These separate contexts can be implemented as threads
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant
ACTION_REQUEST_ENABLE. Its syntax is.
Apart from this constant, there are other constants provided the API , that supports different tasks. They are
listed below.
1 ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth
ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed
ACTION_FOUND
3
This constant is used for receiving information about each device that is discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns asetof bluetooth devices. Its syntaxis.
1 enable()
This method enables the adapter if not enabled
isEnabled()
2
This method returns true if adapter is enabled
disable()
3
This method disables the adapter
getName()
4
This method returns the name of the Bluetooth adapter
setName(String name)
5
This method changes the Bluetooth name
getState()
6
This method returns the current state of the Bluetooth Adapter.
startDiscovery()
7
This method starts the discovery process of the Bluetooth for 120 seconds.
Example
This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and show list
of paired devices by the Bluetooth.
To experiment with this example , you need to run this on an actual device.
Animation:
Animation in android is possible from many ways. In this chapter we will discuss one easy and
widely used way of making animation called tweened animation.
Tween Animation
Tween Animation takes some parameters such as start value , end value, size , time
duration , rotation angle e.t.c and perform the required animation on that object. It can be
applied to any type of object. Soin order tousethis , android has provided usaclasscalled
Animation.
In order toperform animation in android , we are going to call a static function loadAnimation()
of the class AnimationUtils. We are going to receive the result in an instance of Animation
Object. Itssyntaxisasfollows
−
setDuration(long duration)
2
This method sets the duration of an animation.
getDuration()
3
This method gets the duration which is set by above method
end()
4
This method ends the animation.
cancel()
5
This method cancels the animation.
In order to apply this animation to an object ,we will justcall the startAnimation() methodofthe object. Its
syntax is−
Example
The following example demonstrates the use of Animation in android. You would be able to choose
differenttypeofanimationfromthemenuandtheselectedanimationwillbeappliedon animageView on
thescreen.
To experiment with this example , you need to run this on an emulator or an actual device.
Steps Description
1 You will use Android studio IDE to create an Android application and name it as My Application under a package
com.example.sairamkrishna.myapplication.
Camera:
These are the following two ways, in which you can use camera in your application
• Using existing android camera application in our application
• Directly using Camera API provided by android in our application Using
Apartfromtheabove,thereareotheravailableIntentsprovidedbyMediaStore.Theyarelisted as follows
Sr.No Intent type anddescription
1 ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured
2 ACTION_VIDEO_CAPTURE
EXTRA_SCREEN_ORIENTATION
3
It is used to set the orientation of the screen to vertical or landscape
EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage
INTENT_ACTION_VIDEO_CAMERA
5
This intent is used to launch the camera in the video mode
EXTRA_SIZE_LIMIT
6
It is used to specify the size limit of video or image capture size
Now you will use the function startActivityForResult()to launch this activity and wait for its result. Its
syntax is given below
This method has been defined in the activity class. We are calling it from main activity. There are methods
defined in the activity class that does the same job , but used when you are not calling from the activity but
from somewhere else. They are listed below
Sr.No Activity function description
Nomatterwhichfunctionyouusedtolaunchtheactivity,theyallreturntheresult.Theresult canbe
obtained by overriding the function onActivityResult.
Example
Hereisanexamplethatshowshowtolaunchtheexistingcameraapplicationtocaptureanimage anddisplay
the result in the form of bitmap.
Toexperimentwiththisexample,youneedtorunthisonanactualdeviceonwhichcamerais supported.
Steps Description
1 You will use Android studio IDE to create an Android application and name it as Camera under a
com.example.sairamkrishna.myapplication.
Method Description
Method Description
• Video Player:
In android, by using VideoView component and MediaController class we can easily implement
the video player in android applications to play the videos with multiple playback options, such
as play, pause, forward, backward, etc.
Example:
VideoView videoView = (VideoView)findViewById(R.id.vdVw); MediaController
mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri = Uri.parse("android.resource://" + getPackageName() +"/"+
R.raw.video1);
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
• Methods of videoplayer:
Description
Method
• Text to Speech:
Text to speech (TTS) makes an android device read the text and convert it to audio out via
the speaker. Android TTS supports multiple languages. TTSisa simple but powerful feature. It can
also be effectively used in mobile APPs dedicated to visually impaired people orin educational app
for kids or can be used in pronunciation learning app, etc. These are some of the ways you can use
TTS.UsingTextToSpeechenhances interaction betweenthe userandthe mobile application.
• Generally, the android TextToSpeech instance can only be used to synthesize text once it has
completedits initialization soimplement TextToSpeech.OnInitListener tonotify the completion of
initialization.
• Duringtheinitialization,wecansettheaudiopitchrate,audiospeed,typeoflanguage to speak, etc.
based on our requirements.
• OnInitListener-Interfacedefinitionofacallbacktobeinvokedindicatingthecompletion ofthe
TextToSpeech engine initialization.
• TextToSpeechneedstobeinitializedfirst.Forthis,youneedtoimplement the
TextToSpeech.OnInitListener interface and override the method:onInit
TextToSpeech tts = new TextToSpeech(this, this);
public TextToSpeech (Context context, TextToSpeech.OnInitListener listener)
Contants-
• ERROR-Denotes a generic operation failure.
• ERROR_SERVICE-Denotes a failure of a TTS service.
• LANG_AVAILABLE -Denotes the language is available forthe language by the locale
• LANG_COUNTRY_AVAILABLE -Denotes the language is available for the language and
country specified by the locale
• LANG_MISSING_DATA -Denotes the language data is missing.
• LANG_NOT_SUPPORTED-Denotes the language is not supported.
• SUCCESS-Denotes a successful operation.
• QUEUE_FLUSH-Queue mode where all entries in the playback queue (media to be played
andtexttobesynthesized) aredroppedandreplacedbythenewentry.
Classes –
Class Description
SensorEvent The system uses this class tocreate a sensor event object and it
provides the raw sensor data, type of sensor that generated the
event,accuracyofthedata,andthetimestamp for the event.
• getSensorList()
public List<Sensor> getSensorList (int type)
-Use this method to getthe listofavailable sensors ofa certain type. Make multiple calls to get
sensors of different types oruse Sensor.TYPE_ALL toget all the sensors.
• registerListener
public boolean registerListener (SensorEventListener listener, Sensor sensor, int
samplingPeriodUs)
Sensor Class
The android.hardware.Sensor class provides methods to get information of the sensor such as sensor
name, sensor type, sensor resolution, sensor type etc.
The Sensor class defines several constants for accessing the different sensors
Sensor Type Description Common
Uses
TYPE_MAGNETIC_FIELD Hardware Measures the ambient geomagnetic field for all three Creating a
physical axes (x, y, z) in μT. compass.
TYPE_ORIENTATION Software Measuresdegreesof rotationthatadevice makes Determining
around all three physical axes (x, y, z). AsofAPIlevel device
3youcanobtaintheinclination matrixandrotation position.
matrixforadevicebyusing thegravity sensor and the
geomagneticfield sensor in conjunctionwith
the getRotationMatrix() method.
Sensor Class:
You can access the sensor via the sensorManager.getDefaultSensor() method, which takes the sensor
type andthedelay defined as constants on SensorManager as parameters.
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
SensorEvent class-
Its instance is created by the system. It provides information about the sensor.
SensorEventListener interface-
Steps:
1. AndroidprovidesSensorManagerandSensorclassestousethesensorsinour application.In
order tousesensors, firstthingyouneedtodoistoinstantiate theobject of SensorManager class.
It can be achieved as follows.
SensorManager sMgr; sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
2. ThenextthingyouneedtodoistoinstantiatetheobjectofSensorclassbycallingthe
getDefaultSensor() method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
3. Oncethatsensorisdeclared ,youneedtoregisteritslistenerandoverridetwomethodswhichare
onAccuracyChangedandonSensorChanged.Itssyntaxisasfollows−
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL); public
void onAccuracyChanged(Sensor sensor, int accuracy)
{}
public void onSensorChanged(SensorEvent event) { }
Database - Package
The main package is android.database.sqlite that contains the classes to manage your own databases
Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with your database
name and mode as a parameter. It returns an instance of SQLite database which you have to receive in
your own object.Its syntax is given below
SQLiteDatabasemydatabase=openOrCreateDatabase("yourdatabase
name",MODE_PRIVATE,null);
1
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,
DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode.The common flags mode could be
OPEN_READWRITE OPEN_READONLY
2
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
Itissimilartotheabovemethodasitalsoopenstheexistingdatabasebutitdoesnotdefineanyhandlerto handle the
errors ofdatabases
3
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method is equivalent to openDatabase method.
4
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
Thismethodis similar to abovemethod butittakes the Fileobjectas a path rather then astring. It is equivalent to
file.getPath()
Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its
syntax is givenbelow
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the same job
but take some additional parameter is given below
1
execSQL(String sql, Object[] bindArgs)
This method not only insert data , but also used to update or modify already existing data in database using bind
arguments
1
getColumnCount()
This method return the total number of columns of the table.
2
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column
3
getColumnName(int columnIndex)
Thismethod returns thename of the column by specifying the index of the column
4
getColumnNames()
This method returns the array of all the column names of the table.
5
getCount()
This method returns the total number of rows in the cursor
6
getPosition()
This method returns the current position of the cursor in the table
7
isClosed()
This method returns true if the cursor is closed and return false otherwise
Example
Here is an example demonstrating the use of SQLite Database. It creates a basic contacts
applications that allows insertion, deletion and modification of contacts.
To experiment with this example, you need to run this on an actual device on which camera is supported.
Steps Description
2 Modifysrc/MainActivity.javafiletogetreferencesofalltheXMLcomponentsandpopulatethecontacts onlistView.
4 Create a new Activity as DisplayContact.java that will display the contact on the screen
Constructor Description
SQLiteOpenHelper(Context context, String name, creates an object for creating, opening and
SQLiteDatabase.CursorFactory factory, int version) managing the database.
SQLiteOpenHelper(Context context, String name, creates an object for creating, opening and
SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler managing the database. It specifies the
errorHandler) error handler.
There are many methods in SQLiteOpenHelper class. Some of them are as follows:
Method Description
public void onDowngrade(SQLiteDatabase db, int oldVersion, int called when database needs to be
newVersion) downgraded.
SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete, select etc.
Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String inserts a record on the database. The table specifies the table name,
nullColumnHack, ContentValues values) nullColumnHack doesn't allow completely null values. Ifsecond
argumentisnull,androidwillstorenullvaluesif valuesareempty.
Thethirdargumentspecifiesthevaluesto be stored.
Cursor query(String table, String[] columns, returns a cursor over the resultset.
Stringselection, String[] selectionArgs, String
groupBy,String having, String orderBy)
Async Task
What is AsyncTask?
AsyncTask class is used to do background operations that will update the UI(user interface). Mainly
we used it for short operations that will not effect on our main thread.
Android application runs on a single thread when launched. Due to this single thread model tasks that take
longer time to fetch the response can make the application non-responsive. To avoid this we use android
AsyncTask to perform the heavy tasks in background on a dedicated thread and passing the results back
to the UI thread. Hence use of AsyncTask in android application keeps the UI thread responsive
at all times.
Threading rules
• The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
• The task instance must be created on the UI thread.
• execute(Params...) must be invoked on the UI thread.
• Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...),
onProgressUpdate(Progress...) manually.
• The task can be executed only once (an exception will be thrown if a second execution is attempted.)
• Params: the type of the parameters sent to the task upon execution.
• Progress: the type of the progress units published during the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the
type Void:
Example:
Activity_main.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center"
android:background="#FCE9B0">
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Stud_nm"
android:id="@+id/nm"/>
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Stud_mono"
android:id="@+id/no"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="save"
android:onClick="save"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="display"
android:onClick="Display"/>
</LinearLayout>
MainActivity.java
package com.example.asynctaskex26;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
EditText nm,no,mail;
Database db;
asynctask async;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nm=findViewById(R.id.nm);
no=findViewById(R.id.no);
mail=findViewById(R.id.mail);
if((nm.getText().toString()).equals("")&&(no.getText().toString()).equals("")&&(mail.getText().toString()).
equals("")){
Toast.makeText(this, "Enter credentials", Toast.LENGTH_SHORT).show();
}
else {
async.execute(nm.getText().toString(), no.getText().toString(), mail.getText().toString());
nm.setText("");
no.setText("");
mail.setText("");
}
}
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
Context context;
Database db;
AlertDialog.Builder al;
asynctask(Context c){
context=c;
db=new Database(context);
}
@Override
protectedvoid onPreExecute() {
super.onPreExecute();
al=new AlertDialog.Builder(context);
}
@Override
protected Long doInBackground(String... strings) {
String nm = strings[0];
String no = strings[1];
String mail = strings[2];
long result = db.insert(nm, no, mail);
return result;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table std_tbl(name text,contact text,mail text);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Value inserted
SQ LiteDatabase
• It is embedded in android bydefault. So, there is no need to perform any database setup or
administrationtask.
• The package android.database.sqlite contains all the required APIs to use an SQLite
database in our android applications.
• As the name suggests, SQLite is the lightest version of SQL. It does not require
any Server, No configuration.
• The "Lite" in SQLite does not refer to its capabilities. Rather, SQLite is
lightweight when it comes to setup complexity, administrative overhead, and resource
usage.
• In contrast to Other popular RDBMS products like Oracle Database, IBM's DB2, and
Microsoft's SQL Server, SQLite does not require any administrative
overhead or any setup complexity.
SQLiteOpenHeIper class
• For performing any database operation, you have to provide the implementation
ofonCreate()andonupgrade()methodsofSQLiteOpenHelper class.
public DBHelper()
SQLiteDatabase.CursorFactory factory,
int version)
SQLiteOpenHelper(Context creates
context, Stringname, anobjectforcreating,openingand
managing the database. It specifies the
SQLiteDatabase.CursorFactor error handler.
y factory, int
version,
DatabaseErrorHandIer
errorHandler)
SQLiteDatabase.CursorFactory factory,
int version)
SQLiteDatabase class
• Itcontains methods to be performed on sqlite database such as create, update, delete,
SQLiteDatabase.CursorFactory factory,
int version)
SQLiteOpenHelper(Context creates
context, Stringname, anobjectforcreating,openingand
managing the database. It specifies the
SQLiteDatabase.CursorFactor error handler.
y factory, int
version,
DatabaseErrorHandIer
errorHandler)
long insert(String table, String inserts a record on the database. The table
nullCoIumnHack, ContentVaIues specifies the table name, nullColumnHack
values) doesn't allow completely null values. If
second argument is null, android will store null
values if values are empty. The third argument
specifiesthevaluestobestored.
7) Familiarlanguage:Familiarquerylanguagefordatabasedevelopersandadmins.
8) HighlyReliable:TheSQLitedevelopmentteamtakescodetestingandverificationvery serious y.
2
openDatabase(Stringpath, SQLiteDatabase.CursorFactory factory, int flags)
Itissimilartotheabovemethodasitalsoopenstheexistingdatabasebutitdoesnot define any
handler to handle the errors of databases
• Before performing any database operations like insert, update, delete records in a table, first
open the database connection by calling getWritableDatabase() method as shown below:
public DBManager open() throws SQLException
Database - Insertion
• wecancreatetable orinsert data intotableusingexecSQL method defined in
SQLiteDatabase class.
Its syntax is given below
TABLEIFNOTEXISTSlogin(Username
VARCHAR, password VARCHAR);"); mydatabase.execSQL("lNSERT INTO
login VALUES('admin•, 'admin');");
• Thiswillinsertsomevaluesintoourtable inour database.Anothermethodtake some
additional parameter is given below
Following code is use to insert data into the SQL ite database using the insert() method in the android
application.
"Get the Data Repository in write mode
SQLiteDatabase db =this.getWritabIeDatabase();
//Create a new map of values, where column names are the keys
Ifyouobserve above code, weare updatingthe detailsusing update() method based on our
requirements.
• Inandroid, we can delete datafrom the SQLite database using the delete() method in
android applications.
Following code is use to delete the data from the SQL ite database using the delete() method in
the android application.
"Get the Data Repository in write mode
SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_Users,
KEYID*" new
String[]{String.valueOf(userid)});
• If you observe above code, we are deleting the details using delete() method based on
our requirements.
.9.3 Extracting value from cursors
Cursors
• Cursors arewhatcontaintheresultsetofaquery made against adatabase in Android.
• we can retrieve anything from database using an object of the Cursor class. we will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing
tothe table. We can move the cursor forward and retrieve the data.
2 getCoIumnIndex(String columnName)
Thismethodreturnstheindexnumberofacolumnbyspecifyingthenameofthe
column
This method returns the current position of the cursor in the table
• Each move() method returns a boolean to indicate whether the operation was
successfulornot.Thisflagisusefulforiteratingovertherowsina cursor.
• ACursorrepresentstheentireresultset ofthequery. Once thequery isfetched a call to
cursor.moveT0First() ismade.
cursor.moveToFirst(); return
cursor;
• If we are performing any operation on table like INSERT, UPDATE or DELETE a record from table
then we will call it as transaction is happening on table and these transactions will follow ACID
properties to ensure data integrity.
• In any DBMS the database transactions must follow ACID (atomicity, consistency, isolation and
durability) properties to produce consistent results and must be isolated from other
databaseoperations.
• The SQL ite database transactions also follow ACID properties of DBMS to make sure data
transactions consistent throught the database.
stands for Atomic, Consistent, Isolated, and Durable and any transaction happening in
DBMS must possess all these qualities
<ImageView
android:layout_width="match_parent"
android:layout_height="184dp"
android:scaleType="centerCrop"
android:src="@drawable/todo"
/>
<EditText
android:id="@+id/dt"
android:layout_width="240dp"
android:layout_height="48dp"
android:layout_marginStart="80sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="200dp"
android:background="#ffffff"
android:hint="Enter Date " />
<EditText
android:id="@+id/task"
android:layout_width="235dp"
android:layout_height="83dp"
android:layout_gravity="start"
android:layout_marginStart="80sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="270dp"
android:background="#ffffff"
android:hint="Enter task"
android:textAlignment="textStart" />
<Button
android:id="@+id/b1"
android:layout_width="95dp"
android:layout_height="50sp"
android:layout_marginStart="50sp"
<Button
android:id="@+id/b2"
android:layout_width="95dp"
android:layout_height="50sp"
android:layout_marginStart="250sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="400dp"
android:background="#F06292"
android:onClick="display"
android:text="Show" />
<Button
android:id="@+id/b3"
android:layout_width="95dp"
android:layout_height="50sp"
android:layout_marginStart="50sp"
android:layout_marginLeft="50dp"
android:layout_marginTop="500dp"
android:background="#F06292"
android:onClick="delete"
android:text="Delete" />
<Button
android:id="@+id/b4"
android:layout_width="95dp"
android:layout_height="50sp"
android:layout_marginStart="250sp"
android:layout_marginLeft="50dp"
android:layout_marginTop="500dp"
android:background="#F06292"
android:onClick="update"
android:text="Update" />
</RelativeLayout>
MainActicity.java:
package com.example.studdb;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
DBHelper DB;
String s1=dt.getText().toString();
String s2=task.getText().toString();
Boolean check=DB.insertData(s1,s2);
if(check){
Toast.makeText(this, "Task Added :) ", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "Task Not Added :( ", Toast.LENGTH_SHORT).show();
}
}
}
AlertDialog.Builder b1=new AlertDialog.Builder(MainActivity.this);
b1.setTitle("To Do:");
b1.setMessage(br.toString());
b1.setIcon(R.drawable.onbulb);
b1.show();
}
}
public void delete(View view) {
String s1=dt.getText().toString();
Boolean check=DB.deleteData(s1);
if(check==true){
Toast.makeText(this, "Task Deleted", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Task not deleted :( ", Toast.LENGTH_SHORT).show();
DBHelper.java:
package com.example.studdb;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import
android.database.sqlite.SQLiteOpenHelper;public class
DBHelper extends SQLiteOpenHelper { private
SQLiteDatabase DB;
DBHelper(Context context) {
super(context, "TODO1.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase DB) {
DB.execSQL("create table todotbl2(date TEXT ,task TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("drop table if exists todotbl2");
}
Boolean insertData(String dt, String task){
DB=this.getWritableDatabase();
ContentValues c1=new ContentValues();
c1.put("date",dt);
c1.put("task",task);
long result=DB.insert("todotbl2",null,c1);
return result != -1;
}
Boolean updateData(String dt, String task){
DB=this.getWritableDatabase();
outpit:
</LinearLayout>
Mainactivity.java
package com.example.explicitintentfactorialexp18;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
EditText no;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
no=findViewById(R.id.no);
}
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Factorial"
android:textSize="70dp"
android:id="@+id/fact_show"/>
</LinearLayout>
Factorial.java
package com.example.explicitintentfactorialexp18;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
TextView result;
int fact=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_factorial);
result=findViewById(R.id.fact_show);
Intent g=getIntent();
String n=g.getStringExtra("message");
int no=Integer.parseInt(n);
while(no>0){
fact=fact*no;
no=no-1;
}
result.setText(String.valueOf(fact));
}
}
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Theme.FragmentApp.AppBarOverlay"
android:background="#00E676">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="@dimen/appbar_padding"
android:text="@string/app_name"
android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:textColor="#01552C"
android:background="#00E676"/>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00E676" />
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Mainactivity.java
package com.example.fragmentapp;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import com.example.fragmentapp.ui.main.SectionsPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this,
getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
}
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.PlaceholderFragment">
<TextView
android:id="@+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/activity_vertical_margin"
android:layout_marginEnd="@dimen/activity_horizontal_margin"
android:layout_marginStart="@dimen/activity_horizontal_margin"
android:layout_marginTop="@dimen/activity_vertical_margin"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="@+id/constraintLayout"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1" />
</androidx.constraintlayout.widget.ConstraintLayout>
ui.main → PageViewModel.java
package com.example.fragmentapp.ui.main;
import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import
androidx.lifecycle.ViewModelProvider;import
com.example.fragmentapp.R;
/**
* A placeholder fragment containing a simple view.
*/
public class PlaceholderFragment extends Fragment {
@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_main, container, false);
final TextView textView = root.findViewById(R.id.section_label);
pageViewModel.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String s){
textView.setText(s);
}
});
return root;
}
}
ui.main → SectionsPagerAdapter.java
package com.example.fragmentapp.ui.main;
import android.content.Context;
import android.widget.Switch;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.fragmentapp.Gallery;
import com.example.fragmentapp.Music;
import com.example.fragmentapp.R;
import com.example.fragmentapp.Video;
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
@StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2,R.string.tab_text_3};
private final Context mContext;
@Override
public Fragment getItem(int position) {
Fragment f=null;
switch(position){
case 0:
f=new Music();
break;
case 1:
f=new Video();
break;
case 2:
f=new Gallery();
break;
}
return f;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
@Override
public int getCount() {
// Show 2 total pages.
return 3;
}
}
fragment_music.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Music"
android:background="@color/design_default_color_error">
<ImageButton
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="40dp"
android:src="@drawable/play"
android:background="@android:color/transparent"
android:scaleType="fitCenter"/>
<ImageButton
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="40dp"
android:layout_toRightOf="@+id/play"
android:src="@drawable/pause"
android:background="@android:color/transparent"
android:id="@+id/pause"
android:scaleType="fitCenter"/>
<ImageButton
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="40dp"
android:layout_toLeftOf="@+id/play"
android:src="@drawable/stop"
android:background="@android:color/transparent"
android:scaleType="fitCenter"
android:id="@+id/stop"/>
</RelativeLayout>
</FrameLayout>
Music.java
package com.example.fragmentapp;
import android.media.MediaPlayer;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
/**
public Music() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Music.
*/
// TODO: Rename and change types and number of parameters
public static Music newInstance(String param1, String param2) {
Music fragment = new Music();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
pause=root.findViewById(R.id.pause);
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mp!=null){
mp.pause();
}
}
});
stop=root.findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopsong();
}
});
return root;
}
fragment_video.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Video"
<VideoView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/video"
android:layout_gravity="center"/>
</FrameLayout>
Video.java
package com.example.fragmentapp;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.VideoView;
/**
* A simple {@link Fragment} subclass.
* Use the {@link Video#newInstance} factory method to
* create an instance of this fragment.
*/
public class Video extends Fragment {
public Video() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Video.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
fragment_gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Gallery"
android:background="@drawable/frnd">
</FrameLayout>
Gallery.java
package com.example.fragmentapp;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
* Use the {@link Gallery#newInstance} factory method to
* create an instance of this fragment.
*/
public class Gallery extends Fragment {
public Gallery() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Gallery.
*/
// TODO: Rename and change types and number of parameters
public static Gallery newInstance(Stringparam1, String param2){
Gallery fragment = new Gallery();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_gallery, container, false);
}
}
output:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text to \nspeech"
android:textSize="80sp"
android:gravity="center"/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:hint="Text"
android:layout_margin="50dp"
android:textSize="30sp"
android:id="@+id/text"/>
</LinearLayout>
MainActivity.java
package com.example.texttospeech;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextToSpeech ts;
EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text=findViewById(R.id.text);
text.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//ts.speak("Write something",TextToSpeech.QUEUE_FLUSH,null);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//ts.speak(s.toString(),TextToSpeech.QUEUE_FLUSH,null);
}
@Override
public voidafterTextChanged(Editable s){
String s1=text.getText().toString();
String s2;
s2 = new String(String.valueOf(s1.charAt(s1.length()-1)));
ts.speak(s2,TextToSpeech.QUEUE_FLUSH,null);
}
});
ts=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status!=TextToSpeech.ERROR){
ts.setLanguage(Locale.UK);
}
}
});
}
public void onPause(){
if (ts != null) {
ts.stop();
ts.shutdown();
}
super.onPause();
}
}
a s d f
z x c v b n m
?123
</LinearLayout>
Java code:
package com.example.cameraa;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic=findViewById(R.id.pic);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
manifest file:
<uses-permission android:name="android.permission.CAMERA"/>
</LinearLayout>
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.VideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
VideoView videoView=new VideoView(this);
videoView.setVideoURI(data.getData());
videoView.start();
builder.setTitle("Video Recording...");
builder.setView(videoView).show();
}
}
Manifest file:
<uses-feature android:name="android.hardware.camera2"/>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="170dp"
android:fontFamily="sans-serif-condensed-light"
android:text="@string/heading"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textColor="#26A69A"
android:textSize="36sp"
android:textStyle="bold" />
<Button
android:id="@+id/startButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#26A69A"
android:fontFamily="sans-serif-condensed-light"
android:text="@string/startButtonText"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:onClick="s1"
android:textStyle="bold" />
<Button
android:id="@+id/stopButton"
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void s1(View view) {
startService(new Intent( this, NewService.class ) );
}
manifest file:
<service android:name=".NewService"/>
NewService class:
package com.example.servicelifecycle;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
@Override
public int onStartCommand(Intent intent, int flags, int startId) { // execution of service will start on calling
this method
player.setLooping( true ); // providing the boolean value as true to play the audio on loop
<Button
android:id="@+id/b4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50sp"
android:layout_marginLeft="50sp"
android:layout_marginTop="10dp"
android:onClick="list"
android:text="List Devices" />
<Button
android:id="@+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="50sp"
android:layout_marginLeft="50sp"
android:layout_marginTop="10dp"
android:onClick="off"
android:text="Turn OFF"
/>
<ListView
android:id="@+id/l1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:textColor="#ffffff"
/>
</LinearLayout>
Colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="actionbar_text">#ffffff</color>
</resources>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/CustomActionBarTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Styles.xml:
<resources>
</style>
<style name="CustomActionBarTheme"
parent="@style/Theme.AppCompat.Light.DarkActionBar">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<item name="android:actionBarTabTextStyle">@style/MyActionBarTabText</item>
<item name="android:actionMenuTextColor">@color/actionbar_text</item>
</resources>
Java:
package com.example.bluetooth;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
• Javacode-
package com.example.activity_life_cycle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
@Override
protected void onStart() {
super.onStart();
Toast.makeText(getApplicationContext(),"onStart() called",Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(),"onResume()
called",Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
super.onPause();
Toast.makeText(getApplicationContext(),"onPause() called",Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText(getApplicationContext(),"onStop() called",Toast.LENGTH_SHORT).show();
}
@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(getApplicationContext(),"onRestart()
called",Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(),"onDestroy()
called",Toast.LENGTH_SHORT).show();
}
}
• Output-
• MainActivity.java-
package com.example.broadcastreceiver1;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onStart() {
super.onStart();
registerReceiver(bc,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
registerReceiver(bc,new IntentFilter(Intent.ACTION_BATTERY_LOW));
registerReceiver(bc,new IntentFilter(Intent.ACTION_POWER_CONNECTED));
registerReceiver(bc,new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));
registerReceiver(bc,new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
registerReceiver(bc,new IntentFilter(Intent.ACTION_BUG_REPORT));
registerReceiver(bc,new IntentFilter(Intent.ACTION_REBOOT));
registerReceiver(bc,new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
registerReceiver(bc,new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(bc);
}
}BroadcastRec.java-
package com.example.broadcastreceiver1;
import org.w3c.dom.Text;
}
if(Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())){
boolean mode=intent.getBooleanExtra("state",false);
if(mode)
Output-
Animation:
• Xml code-
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/android"
android:id="@+id/img"
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lv"
android:layout_margin="50dp"
/>
</LinearLayout>
• Java code-
package com.example.animation;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
}
});
}
• fadeIn.xml
• string.xml-
<resources>
<string name="app_name">Animation</string>
<string-array name="animationStyle">
<item>Clockwie/Anti Clockwise</item>
<item>Zomm In/Out</item>
<item>Fade In/Out</item>
</string-array>
</resources>
• Output-
android:layout_height="wrap_content"
android:id="@+id/cls"
android:hint="Class"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert Record"
android:layout_marginTop="50dp"
android:onClick="clk"/>
</LinearLayout>
MainActivity.java-
• package com.example.exp_26;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
async=new Async(this);
}
• Async.java-
package com.example.exp_26;
import android.app.ProgressDialog;
import android.content.Context;
• DbClass.java-
package com.example.exp_26;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table tbl_stud(roll TEXT,name TEXT,class TEXT)");
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long insert(String r,String n,String c){
SQLiteDatabase db=getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("roll",r);
contentValues.put("name",n);
contentValues.put("class",c);
long l=db.insert("tbl_stud",null,contentValues);
return l;
}
}
• Output-
3ebir 8edge
Tabe: sbud
name class
Filter Filter Filter
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="50dp"
android:hint="Name"
android:textSize="20dp"
android:id="@+id/nm"
/>
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="50dp"
android:hint="Mobile"
android:textSize="20dp"
android:id="@+id/mob"
/>
<Button
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="50dp"
android:text="Add To Contacts"
android:textSize="20dp"
android:id="@+id/add"
android:onClick="addContact"
/>
<Button
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginTop="50dp"
android:text="Contacts List"
android:textSize="20dp"
android:id="@+id/list"
android:onClick="showContact"
/>
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nm=findViewById(R.id.nm);
mob=findViewById(R.id.mob);
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Output:
1 ArrayList<String> divideMessage(Stringtext)
This method divides a message text into several fragments, none bigger than the maximum
SMS messagesize.
SmsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null,"sms message", null, null);
SMSManager API required SEND_SMS permission in our android manifest to send
SMS.FollowingisthecodesnippettosetSEND_SMSpermissionsin manifest file.
<uses-permission android:name="android.permission.SEND_SMS"/>
In android, we can easily send an email from our android application using existing email
clientssuchasGMAIL,Outlook,etc.insteadofbuildinganemailclientfromscratch.
Generally, the Intent object in android with proper action (ACTION_SEND) and data
willhelpustolaunchtheavailableemailclientstosendanemailinour application.
In android, Intent is a messaging object which is used to request an action from
another app component such as activities, services, broadcast receivers, and content
providers.
TosendanemailusingtheIntentobjectinandroidapplication,weneedtowritethe code as
shown below.
1
EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.
2
EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.
3
EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.
4
EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to supply an alternative to
EXTRA_TEXT as HTML formatted text.
5
EXTRA_SUBJECT
A constant string holding the desired subject line of a message.
To send an email you need to specify mailto: as URI using setData() method and data type will be
to text/plain using setType() method as follows −
emailIntent.setData(Uri.parse("mailto:")); emailIntent.setType("text/plain");
For below example code is present in folder email refer all files
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
What is Email?
• Email is messages distributed by electronic means from one system user to one or more recipients via a
network.
• Intent is carrying data from one component to another component with-in the application or outside
• the application.
• Send an email from your application, you don’t have to implement an email client from the starting
,butyoucanuseanexistingone likethedefaultEmailappproviding from Android, Gmail, Outlooketc.
• For this purpose, we need to write an Activity that launches an email client, using an implicit Intent
with the right action and data.
• To send an email from our app by using an Intent object that launches existing email clients.
• EXTRA_SUBJECT
▪ A constant string holding the desired subject line of a message.
• EXTRA_TEXT
▪ A constant CharSequence that is associated with the Intent, used with ACTION_SEND to
supply the literal data to be sent.
• ACTION_SEND :
o TheuserchoosefromseveralActivities,evenifyousetType(“text/plain"), becausethatApp/Activities
can manage all file types and so even email message files. The solution is in the setSelector method
• setType :
▪ setType(String mimeType) input param is represent the MIME type datathat uwant to get in
return from firing intent.
▪ By using one of following MIME type you can force user to pick option which you desire.
Please take a Note here, All MIME types in android are in lowercase.
setType :
Methods Description
snapshot(GoogleMap.SnapshotReadyCallback Thismethodtakesasnapshotofthemap.
callback)
• Here add a fragment element to the activity‟s layout file to define a Fragment
object. In this element, set the android:name attribute to
“com.google.android.gms.maps.MapFragment”. This automatically attaches a
MapFragmenttotheactivity.Thefollowinglayoutfilecontains a fragmentelement:
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.abhiandroid.GoogleMaps.googlemaps.MapsActivity"/>
Or
A class for handling geocoding and reverse geocoding. Geocoding is the process of
transforming a street address or other description of a location into a (latitude, longitude)
coordinate. Reverse geocoding is the process of transforming a (latitude, longitude)
coordinate into a (partial) address. The amount of detail in a reverse geocoded location
description may vary, for example one might contain the full street address of the closest
building,whileanothermightcontainonlyacityname and postal code
Geocoder
Android Geocoder class is used for Geocoding as well as Reverse Geocoding.
Geocoding refers to transforming street address or any address into latitude and longitude.
Reverse Geocoding refers to transforming latitude and longitude into its corresponding
street address.
Address class helps in fetching the street address, locality, sub-locality, city, country, landmark
etc. features of the location.
• publicdoublegetLatitude()-Returnsthelatitudeofthe addressifknown
• public String getLocality ()-Returns the locality of the address, for example
"Mountain View", or null if it is unknown.
• publicdoublegetLongitude()-Returnsthelongitudeoftheaddressifknown.
• public String getPhone ()- Returns the phone number of the address if known, or null if
it is unknown.
• public String getPostalCode ()Returns the postal code of the address, for
example "94110", or null if it is unknown.
• publicStringgetPremises()Returnsthepremisesoftheaddress,ornullifitis unknown.
• publicbooleanhasLatitude()-Returnstrueifalatitudehasbeenassignedto this
Address, falseotherwise.
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.javapapers.com.androidgeocodelocation" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission android:name="android.permission.INTERNET"/>
<application android:allowBackup="true"
android:icon="@drawable/ic_launcher" android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Step 2: Accessing the Geo Location for Lat and Long
Following class is the key element in accessing the latitude and longitude of the Android
device.It implementsthe LocationListener andgets thelocationcoordinate updates.Wehave
designed our requirement not to be a continous update for location. On demand we will get the
location coordinates.
import android.app.Activity;import
android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler; import
android.os.Message; import
android.provider.Settings; import
android.view.View; import
android.widget.Button;
AppLocationService appLocationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
tvAddress =(TextView)findViewById(R.id.tvAddress);
appLocationService = new AppLocationService(
MyActivity.this);
//you can hard-code the lat & long if you have issues with getting it
//remove the below if-condition and use the following couple of lines
//double latitude = 37.422005;
//double longitude = -122.084095
if (location != null) {
}
});
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Location"
android:id="@+id/btnGPSShowLocation"
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Address"
android:id="@+id/btnShowAddress"
android:layout_toEndOf="@+id/tvAddress"
android:layout_below="@+id/btnGPSShowLocation"
android:layout_alignParentStart="true" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tvAddress"
android:layout_alignParentBottom="true"
android:layout_marginBottom="134dp"
android:layout_alignParentEnd="true" />
</RelativeLayout>
a) Threat Model
b) Android platform securitymodel
1. Threat Model
Mobile platforms is a targetable area to malware attacks because various mobile platforms
have powerful ability to store a large amount of data (sensitive) Malicious-Basedon
theresearchesandarticlesApplicationstherearesomeof themalwarethreatshavebeen
addressed such as by static and dynamic analysis of application binaries, enhanced
application installers, novel run-time privacy
Android application has been signed with a certificate with a private key Know the ownerof the
application is unique. This allows the author of The application will be identified ifneeded.
When an application is installed in The phone is assigned a user ID, thus avoiding it from
affectingitOtherapplicationsbycreatingasandboxforit.
It is mandatory for an application to list all the resources it will Access during installation.
Terms are required of an application, in The installation process should be user-based or
interactive Checkwith thesignature oftheapplication.
The purpose of a permission is to protect the privacy of an Android user. Android apps must
request permission to access sensitive user data (such as contacts and SMS), as well as
certain system features (such as camera and internet). Depending on the feature, the system
might grant the permission automatically or might prompt the user to approve the request.
• Design review: The Android security process begins early in the development lifecycle
withthecreationofarichandconfigurablesecuritymodelanddesign.Each majorfeatureofthe
platform is reviewed by engineering and security resources, with appropriatesecurity controls
integrated into the architecture of the system.
• Penetration testing and code review: During the development of the platform, Android-
created and open source components are subject to vigorous security reviews. These
reviews are performed by the Android Security Team, Google‟s Information Security
Engineering team, and independent security consultants. The goal of these reviews is to
identify weaknesses and possible vulnerabilities well
• Open source and community review: AOSP enables broad security review by any interested
party. Android also uses open source technologies that have undergone significant external
security review, such as the Linux kernel. Google Play provides a forum for users and
companies to provide information about specific apps directly to users.
• Incident response: Even with these precautions, security issues may occur after shipping,
which is why the Android project has created a comprehensive security response process.
Full-time Android security team members monitor the Android- specific and the general
security community for discussion of potential vulnerabilities and review security bugs
filed on the Android bug database. Upon the discovery of legitimate issues, the Android
team has a response process that enables the rapid mitigation of vulnerabilities to ensure
that potential risk to all Android users is minimized
• Monthly security updates: The Android security team provides monthly updates to Google
Android devices and allourdevice manufacturing partners.
New Users: Before you can start using the Google Maps Platform APIs and SDKs, youmust
signupandcreateabillingaccount.TousethePlacesAPIyoumust haveanAPIkey.The
APIkey isaunique identifier that is used toauthenticate requestsassociatedwithyour
projectforusageandbillingpurposes.
an APIkey:
Documenting the process of publishing an app on the Google Play Store as I go through it
forthe first time.
Step 1: Sign up
Sign up for an account onthe Android Developer Console. Creating an account costs
$25.
• Hi-res icon: I used the launcher icon. It was an SVG file, so I converted it to PNG using
GIMP.
• Set the android:versionName attribute in the manifest tag in manifest.xml. This string is
shown to users and has no other purpose.
I chose “1.0”.
• Losing a key-pair consequences that you will not be able to push updates to your app.
Google will perform acheck onthe APK. My appwas using an SVG forthe launcher icon,
whichisno-bueno.IhadtochangeittoPNGandrecreatethesignedAPK.
Step 7:
Complete the checklist on the left until all the items have a green checkmark. The consolere-
evaluatesthechecklisteverytimeyouclickSaveDraftinthetopright.
Email:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#1DE9B6"
tools:context=".MainActivity">
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:id="@+id/to"
android:hint="To"
/>
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:id="@+id/sub"
android:hint="Subject"
android:layout_marginTop="40dp"
/>
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:id="@+id/msg"
android:hint="Message"
android:layout_marginTop="40dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:layout_marginTop="50dp"
android:onClick="send"
/></LinearLayout> Java code:
package com.example.emailsend;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1=findViewById(R.id.to);
e2=findViewById(R.id.sub);
e3=findViewById(R.id.msg);
}
Java code:
package com.example.exp31;
import androidx.fragment.app.FragmentActivity;
import android.graphics.Color;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
}
• Manifest.xml-
</manifest>
• Output-
• Java code:
package com.example.map4;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public voidonMapReady(GoogleMap googleMap){
mMap = googleMap;
}
}
• Output-
• Xml code-
<resources>
• Java code-
package com.example.map2;
import androidx.fragment.app.FragmentActivity;
import android.graphics.Color;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
• Output-
***