Master+Android+App+Development+eBook+ +Abhi+Android
Master+Android+App+Development+eBook+ +Abhi+Android
Version3.0
MASTERANDROIDAPP
DEVELOPMENTeBOOK
___
ByAbhiAndroid
0
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
1
WelcomeMessage
Thankyoufordownloadingthisguide…
Hi,
AbhiAndroid'smissionistohelppeoplelearnAndroidDevelopmentwithstepbystep
explanation.Toachievethat,wedoourbesttoexplaineverytopicintheeasiestwaypossible.
Wemakesureeverytutorialorcoursewecreateistopquality.
Hopeyoulikethisfreeguide.Pleaseshareyourfeedbackbyemailingusat
support@abhiandroid.com
PS:Ialsolookforwardtoseeingyouinsideourcourse.
Withlove&respect,
AbhishekSaini
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
2
MasterAndroidApp
DevelopmentCourse
Beforeyoustartreadingthisguide,Iwouldliketosharelittledetailsaboutourvideotraining:
Ourmottowiththevideotrainingis:B
ytheexperienceddevelopersandforeveryAndroid
Developerprovidingstepbystepexplanationofeverytopicwithcode.
-Stepbystepexplanation
-Masterandroiddevelopmentandboostyourconfidence
-Newcontentgetsaddedeverymonth
-Bonus(Premiumprojectsourcecode,certificateofcompletionandmore)
Youcanaccessthecoursehere:h
ttps://abhiandroid.com/course/
Note:Wealsooffer7daysmoneybackguaranteewithnoquestionsasked.
ImportantMessage
Thiscopyispurelydedicatedtoyou.Youcanuseitinseveralways.Saveitinyourlaptop,
mobile,takeaprintout,andplease,noneedtosaythanks.Butyoucan’tsellitoryoucan’t
makeachangeinitbecauseallrightsofthiscopyiswithAbhiAndroid.com.Ifyouwantsome
changesinitorsomeadditiontoit,youcanmailmeatinfo@abhiandroid.com.And,ifyoulike
thisguide,don’tforgettoshareitwithyourbuddies.I’msuretheywillappreciateit.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
3
TablesOfContent
1. istoryofAndroid……………………………………………………………………………..Page4
H
2. XMLinAndroid………………………………………………………………………………...Page7
3. ActivityLifecycleinAndroid…………………………………………………………………..Page17
4. Linearlayout….………………………………………………………………………………….Page28
5. RelativeLayout…………………………………………………………………………………Page36
6. TableLayout…………………………………………………………………………………….Page54
7. FrameLayout…………………………………………………………………………………...Page64
8. Adapter.……………………………………………………………………………………….....Page73
9. ListView.………………………………………………………………………………………...Page82
10. GridView.………………………………………………………………………………………..Page94
11. TextView.……………………………………………………………………………………….Page110
12. ScrollView.……………………………………………………………………………………..Page120
13. Spinner.…………………………………………………………………………………………Page129
14. EditText.……………………………………………………………………………………...…Page 134
15. Button.…………………………………………………………………………………………..Page148
16. ImageView.……………………………………………………………………………………..Page160
17. ImageButton…………………………………………………………………………….………Page169
18. CheckBox…………………………………………………………………………...…………..Page177
19. Switch……….…………………………………………………………………………………..Page191
20. RadioButton&RadioGroup…………………………………………….……………………...Page205
21. RatingBar…….………………………………………………………………………………….Page220
22. WebView…….…………………………………………………………………………………..Page232
23. AutocompleteTextview…………………………………………………………………………Page242
24. ProgressBar…….……………………………………………………………………………….Page252
25. TimePicker…….………………………………………………………………………………...Page266
26. CalendarView….………………………………………………………………………………..Page280
27. ExpandableListView……………………………………………………………………………Page298
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
4
28. Chronometer………………………………………………………………………………….…Page317
29. ZoomControls…………………………………………………………………………………..Page332
30. VideoView…………………………………………………………………………………..…...Page343
31. SearchView………………………………………………………………………………….......Page356
32. Toast……………………………………………………………………………………………...Page370
33. IntentinAndroid………………………………………………………....……………………...Page378
34. InternalStorage……………………………………………………………….………………...Page389
35. ExternalStorage………………………………………………………………………..……….Page399
36. SharedPreference……………………………………………………………………..………Page409
37. Sqlite…………………………………………………………………………...………..……….Page423
38. JsonParsing……………………………………………………………………………………...Page435
39. Asynctask………………………………………………………………………………………...Page451
40. SplashScreen…………………………………………………………………………………...Page461
41. HTMLinAndroid…………………………………………………………………………………Page473
42. Fragment…………………………………………………………………………………………Page485
43. BasicCalculatorApp…………………………………………………...………….…..………Page501
44. YoutubeAndroidApp………………………………………....……………...………..………Page512
45. CountdownTimerAndroidApp…………………………....…...…………...………..………Page525
46. PremiumAndroidAppSourceCode…………………………………………………………..Page532
HistoryofAndroid
AndroidisaLinuxBasedOperatingSystembyGOOGLEwhichprovidesarichapplication
Frameworkandhelpsindevelopinginteractiveapplications.TheOSfirstOSversionwas
introducedin2007withmanyofitsversionsnamedinAlphabeticalorderrangingfromA-Nand
upcomingisO.
HEREISDETAILEDABOUTANDROIDVERSIONS:
Alpha–Inthis(Android1.0)wasthefirstversionsofAndroidoperatingSystembyGoogle.It
hasbasicfunctionalitywithasimplebrowserandotherGoogleappslikeGmail,Mapsand
YouTube.
Beta– LateronwithAndroid1.1fewmorefunctionalityadded,theAPIchangesfromLevel1
inAndroid1.0toLevel2.ItsupportsattachmentwithMMS.
Cupcake–CupcakewasAndroidsecondversionwithnewfeaturesaswellastheAndroid
frameworkAPIupdated.ItwasAndroid1.5withonScreenKeyboard,BluetoothandUpdatedUI
forapplications.
Donut–ItwasAndroid1.6nicknamedasDONUT.ItaddedsupportforCDMA,additional
screensizes,talktospeechengineandbatteryindicator.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
5
Eclair–A
ndroid2.0-2.1aslikeotherversionsthisalsocomeupwithanicknameasECLAIR
andlotmorefunctions&features.ItcomeupwithBluetooth2.1,livewallpaper,HTML5
support,abilitytosearchsms&mms,flashsupport,digitalzoomandmorecamerafeatures
Froyo–Androidversion2.2-2.2.3introducedwithUSBtethering&WiFihotspotfunctionality
andappscannowbeinstalledonmemorycard.SupportAdobeflash,increasedspeedand
performanceofapplicationswithnewfeatures.
Gingerbread–Gingerbread(Android2.3-2.3.7)introducedwithupdatedUserInterfacewhich
providemoreeasetouse.Featuresarelikesensors,multiplecameras(Front&back),virtual
keyboard,bettertextsuggestion,voiceinputcapabilityandpressholdcopypastecapability.
Honeycomb–ThisAndroidplatformHoneycombwasdesignedforlargescreensliketabletsso
interfaceelementslikevirtualkeyboardoptimizedforbiggerscreen.Homescreenisoptimized,
tabsareintroducedinbrowserwithadditionalincognitomodeandvideochat&Gtalkis
supported.
IceCreamSandwich–I ceCreamsandwichcomein2011bringingallnewlook.Itgivesmore
easetouserlikeusercanquicklyswipetoclosetheapps,newgallerylayoutandbuiltinphoto
editor.
JellyBean–GooglemadeOperatingSystemmoreresponsivewithJellyBeanandintroduces
filesharingwithAndroidBeam.Restrictedprofile,DialPadcomplete,supportedother
languageslikeHindi,changedcameraUI.
KitKat–Kitkatcomeupin2013withAPILevel19.Ithaswirelessprintingcapability,new
dailerid,chromewebviewandscreenrecording.
Lollipop–Androidversion5.0-5.1.1comeupwithimprovedRAMandbatterymanagement.
FurtherrestylingthroughMaterialdesign,nointerruptsfeature,unlockphonethrough
Bluetoothtrusteddevices,printpreviewsandsmartlockfeature.
Marshmallow–Marshmallowwasreleasedinyear2015,comeupwithsmarterbatteryand
dozemode(itpreventscertaintaskfromrunningifthephonebeingsettingidle),NowOnTap,
betterprivacysettings,easiertoupgradephone,Fingerprintsensorandbuiltinvisualvoice
mail.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
6
Nougat–A
ndroidNougatwasmadeofficialin2016withupdatedemoji,72newlyadded,multi
windowview(switchbetweenappswithdoubletap),smarterbatterywithdatasavermode,
moresecuredandhighqualityvirtualrealitywithnewdimensions.
Oreo–I tisthe15thversionoftheAndroidmobileoperatingsystemreleasedtothepublicon
August21,2017.Itcontainsanumberofmajorfeatures,includingnotificationgrouping,
picture-in-picturesupportforvideo,performanceimprovements,andbatteryusage
optimizationetc.
Pie–A
ndroidpieisthe16thversionoftheAndroidmobileoperatingsystemreleasedpublicly
onAugust6,2018withupdatedfeatures,NewGestureNavigation,AdaptiveBatteryand
Brightness,AppActions,Slices,NewAccessibilityMenuandImprovedSecurityFeatures.
Android10–T
hestableversionofAndroid10wasreleasedonSeptember3,2019comewith
Gesturenavigation,LiveCaption,SmartReply,SoundAmplifier,Privacycontrols.,Location
controlsandSecurityupdates
Android11–A
ndroid11wasfirstannouncedbyGoogleonFebruary19,2020,andthefirst
developerpreviewreleasedonthesamedaycomeswithDynamicmediacontrols,built-in
screenrecorder,Chatbubbles,Screenrecorder,Notificationhistory,One-timepermission,
Permissionsauto-resetetc.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
7
XMLinAndroid
XMLstandsforExtensibleMarkupLanguage.XMLisamarkuplanguagemuchlikeHTMLused
todescribedata. XMLtagsarenotpredefinedinXML.WemustdefineourownTags.Xmlas
itselfiswellreadablebothbyhumanandmachine.Also,itisscalableandsimpletodevelop.In
Androidweusexmlfordesigningourlayoutsbecausexmlislightweightlanguagesoitdoesn’t
makeourlayoutheavy.
InthisarticlewewillgothroughthebasicconceptsofxmlinAndroidanddifferentXMLfiles
usedfordifferentpurposeinAndroid.ThiswillhelpyouinwritingaUIcodetodesignyour
desireduserinterface.
BasicsOfUserInterface:
ThewholeconceptofAndroidUserInterfaceisdefinedusingthehierarchyofViewand
ViewGroupobjects.AViewGroupisaninvisiblecontainerthatorganizeschildviews.These
childviewsareotherwidgetswhichareusedtomakethedifferentpartsofUI.OneViewGroup
canhaveanotherViewGroupasanchildelementasshowninthefiguregivenbelow:
HereinaboveDiagramViewGroup(LinearLayout)containsoneViewGroup(i.e.Relative
Layout)andtwoView(ButtonandTextView).FurthertwomoreView(i.e.2EditText)arenested
insideRelativeLayoutViewGroup.Itisimportanttonotethatonelayoutcanbenestedin
anotherlayout.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
8
Thebelowcodesnippetwillexplaintheaboveimageinbetterway.Pasteitin
activity_main.xml:
<?
xml
version="1.0"
encoding ="
utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android
:orientation ="vertical" android :l
ayout_width
="match_parent"
android
:layout_height ="match_parent">
<Button
android
:id
="
@+id/buton1"
android
:layout_width ="
wrap_content"
android
:layout_height ="wrap_content"
android
:text="
Button" />
<TextView
android
:id
="
@+id/textView1"
android
:layout_width ="
wrap_content"
android
:layout_height ="wrap_content"
android
:text="
sample Text"
android
:layout_marginTop ="
15dp"
android
:textSize ="
30dp" />
<RelativeLayout
android
:layout_width ="
match_parent"
android
:layout_height ="match_parent">
<EditText
android
:id
="
@+id/editTextName"
android
:layout_width ="
wrap_content"
android
:layout_height ="wrap_content"
android
:hint="
First Name"
/
>
<EditText
android
:id
="
@+id/editTextLastName"
android
:layout_width ="
wrap_content"
android
:layout_height ="wrap_content"
android
:hint="
LastName" />
<
/RelativeLayout>
</LinearLayout>
EveryAndroidapplicationscreenhassomecomponentslikebutton,Textorimages.Theseare
containedinsidetheViewGroup.LayoutsarethebestexamplesforViewGroups.Thedifferent
typesoflayoutinandroidareLinearLayout,RelativeLayout,AbsoluteLayout,TableLayoutand
FrameLayout.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
9
DifferentXMLFilesUsedinAndroid:
InAndroidthereareseveralxmlfilesusedforseveraldifferentpurposes.Belowwedefineeach
andeveryone.
1.LayoutXMLFiles:LayoutxmlfilesareusedtodefinetheactualUI(Userinterface)ofour
application.Itholdsalltheelements(views)orthetoolsthatwewanttouseinourapplication.
LiketheTextView’s,Button’sandotherUIelements.
LocationinAndroidStudio:
Youwillfindoutthisfileinsidetheresfolderandinsideitthereisanotherfoldernamedlayout
whereyouwillgetallthelayoutfilesfortheirrespectiveactivitiesorfragments.
BasicLayoutXMLCode:
Belowweshowactivity_main.xmlfileinwhichwehavetwoTextView’s.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
10
2.ManifestxmlFile(Mainfest.xml):T
hisxmlisusedtodefineallthecomponentsofour
application.Itincludesthenamesofourapplicationpackages,ourActivities,receivers,services
andthepermissionsthatourapplicationneeds.ForExample–Supposeweneedtouseinternet
inourappthenweneedtodefineInternetpermissioninthisfile.
LocationinAndroidStudio:
Itislocatedinsideapp>manifestsfolder
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
11
DefiningInternetPermissioninAndroidManifest.xml
BelowweshowtheA
ndroidManifest.xmlfileanddefinetheInternetPermissioninthatfile.
<?
xml
version ="
1.0"
encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package
="example.abhiandroid.MyApplication" > <
!--
applicationp
ackage
name-
->
<uses-permission android:name ="
ANDROID.PERMISSION.INTERNET" /
>
<!--
define Internet Permission-->
<application
android
:allowBackup ="
true"
android
:icon ="@mipmap/ic_launcher"
android
:label ="
@string/app_name"
android
:theme ="
@style/AppTheme">
<!--
add your Activities, Receivers, Services
NamesHere
-->
<activity
android
:name =".MainActivity"
android
:label ="
@string/app_name">
<intent-filter>
<actiona
ndroid:name ="android.intent.action.MAIN" />
<category android:name ="
android.intent.category.LAUNCHER" /
>
</intent-filter>
</activity>
</application>
</manifest>
3.StringsxmlFile(strings.xml):T
hisxmlfileisusedtoreplacetheHard-codedstrings
withasinglestring.Wedefineallthestringsinthisxmlfileandthenaccesstheminour
app(Activityorin LayoutXMLfiles)fromthisfile.Thisfileenhancethereusabilityofthecode.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
12
LocationinAndroidStudio:
Belowweshows trings.xmlfileanddefineastringinthefile.
<resources>
<string
n
ame
="app_name"
>M
yApplication
</string>
<string
n
ame
="hello_world">H
ello
world!</string>
<string
n
ame
="action_settings">S
ettings</string>
<string
n
ame
="login"
>U
serLogin
</string>
<!--
defineyour
stringshere
-->
</resources>
4.StylesxmlFile(styles.xml):Thisxmlisusedtodefinedifferentstylesandlooksforthe
UI(UserInterface)ofapplication.Wedefineourcustomthemesandstylesinthisfile.
LocationinAndroidStudio:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
13
Belowweshowthes tyle.xmlfile.
<resources>
<!--
Base application
theme.
-->
<stylen
ame="
AppTheme"
p
arent
="
Theme.AppCompat.Light.DarkActionBar">
<!--
Customize your
theme
here.
-->
</style>
</resources>
5.DrawablexmlFiles:T
hesearethosexmlfilesthatareusedtoprovidevariousgraphicsto
theelementsorviewsofapplication.WhenweneedtocreateacustomUIweusedrawablexml
files.SupposeifweneedtodefineagradientcolorinthebackgroundofButtonoranycustom
shapeforaviewthenwecreateaDrawablexmlfileandsetitinthebackgroundofView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
14
Belowweshowcustom_drawable.xmlfileandcreateagradientbackgroundcolorusingstyle
attribute.
<?
xml
version ="
1.0"encoding
="utf-8"
?>
<shapex
mlns:android ="
http://schemas.android.com/apk/res/android">
<!--
define start,centerandend
colorfor
gradient
-->
<gradient
android:centerColor="
#0f0"
android:endColor
="#00f"
android:startColor="
#f00"/
>
</shape>
6.ColorxmlFile(colors.xml):T
hisfileisusedtodefinethecolorcodesthatweusedinour
app.Wesimplydefinethecolor’sinthisfileandusedtheminourappfromthisfile.
LocationinAndroidStudio
Belowweshowthecolors.xmlfileinwhichwedefinegreenandwhitecolor.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
15
<?
xml
version ="
1.0"
encoding="
utf-8"
?>
<resources>
<!--
define your
colors
Here-->
<colorn
ame
="
greenColor">#0f0
</color>
<colorn
ame
="
white">#
fff
</color>
</resources>
7.DimensionxmlFile(dimens.xml):T
hisxmlfileisusedtodefinethedimensionsofthe
View’s.SupposeweneedaButtonwith50dp(densitypixel)heightthenwedefinethevalue
50dpindimens.xmlfileandthenuseitinourappfromthisfile.
LocationinAndroidStudio:
Belowweshowthedimens.xmlfileinwhichwedefine50dp dimensionforButtonheight.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
16
<resources>
<!--
Default screen
margins,
per
the
AndroidDesign
guidelines.-->
<dimenn
ame
="
activity_horizontal_margin" >1
6dp
</dimen>
<dimenn
ame
="
activity_vertical_margin">1
6dp</dimen><dimen
n
ame
="btnheight"
>5
0dp
</dimen>
</resources>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
17
ActivityLifecycleinAndroid
ActivityLifecycle:A
ctivityisoneofthebuildingblocksofAndroidOS.Insimplewords
Activityisascreenthatuserinteractwith.EveryActivityinandroidhaslifecyclelikecreated,
started,resumed,paused,stoppedordestroyed.ThesedifferentstatesareknownasActivity
Lifecycle.InotherwordswecansayActivityisaclasspre-writteninJavaProgramming.
BelowisActivityLifecycleTable:
ShortdescriptionofActivityLifecycleexample:
onCreate()–Calledwhentheactivityisfirstcreated
onStart()–Calledjustafterit’screationorbyrestartmethodafteronStop().HereActivitystart
becomingvisibletouser
onResume()–
CalledwhenActivityisvisibletouserandusercaninteractwithit
onPause()–CalledwhenActivitycontentisnotvisiblebecauseuserresumepreviousactivity
onStop()–
Calledwhenactivityisnotvisibletouserbecausesomeotheractivitytakesplaceof
it
onRestart()–Calledwhenusercomesonscreenorresumetheactivitywhichwasstopped
onDestroy()–CalledwhenActivityisnotinbackground
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
18
BelowActivityLifecycleDiagramShowsDifferentStates:
DifferentTypesofActivityLifecycleStates:
Activityhavedifferentstatesorit’sknownasActivitylifecycle.Alllifecyclemethodsaren’t
requiredtooverridebutit’squiteimportanttounderstandthem.Lifecyclesmethodscanbe
overriddenaccordingtorequirements.
LISTOFACTIVITYLIFECYCLEMETHODSORSTATES:
ActivityCreated:onCreate(BundlesavedInstanceState):
onCreate()methodiscalledwhenactivitygetsmemoryintheOS.Tousecreatestateweneed
tooverrideonCreate(BundlesavedInstanceState)method.Nowtherewillbequestioninmind
whatisBundlehere,soBundleisadatarepositoryobjectthatcanstoreanykindofprimitive
dataandthisobjectwillbenulluntilsomedataisn’tsavedinthat.
WhenanActivityfirstcallorlaunchedthenonCreate(BundlesavedInstanceState)methodis
responsibletocreatetheactivity.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
19
Wheneverorientation(i.e.fromhorizontaltoverticalorverticaltohorizontal)ofactivitygets
changedorwhenanActivitygetsforcefullyterminatedbyanyOperatingSystemthen
savedInstanceStatei.e.objectofBundleClasswillsavethestateofanActivity.
Itisbestplacetoputinitializationcode.
ActivityStarted:onStart():
onStart()methodiscalledjustafterit’screation.InothercaseActivitycanalsobestartedby
callingrestartmethodi.eafteractivitystop.SothismeansonStart()getscalledbyAndroidOS
whenuserswitchbetweenapplications.Forexample,ifauserwasusingApplicationAandthen
anotificationcomesanduserclickedonnotificationandmovedtoApplicationB,inthiscase
ApplicationAwillbepaused.AndagainifauseragainclickonappiconofApplicationAthen
ApplicationAwhichwasstoppedwillagaingetsstarted.
ActivityResumed:.onResume():
Activityresumedisthatsituationwhenitisactuallyvisibletousermeansthedatadisplayedin
theactivityisvisibletouser.Inlifecycleitalwaysgetscalledafteractivitystartandinmostuse
caseafteractivitypaused(onPause).
ActivityPaused:onPause():
Activityiscalledpausedwhenit’scontentisnotvisibletouser,inmostcaseonPause()method
calledbyAndroidOSwhenuserpressHomebutton(CenterButtononDevice)tomakehide.
Activityalsogetspausedbeforestopcalledincaseuserpressthebacknavigationbutton.The
activitywillgoinpausedstateforthesereasonsalsoifanotificationorsomeotherdialogis
overlayinganypart(toporbottom)oftheactivity(screen).Similarly,iftheotherscreenor
dialogistransparentthenusercanseethescreenbutcannotinteractwithit.Forexample,ifa
callornotificationcomesin,theuserwillgettheopportunitytotakethecallorignoreit.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
20
ActivityStopped:onStop():
Activityiscalledstoppedwhenit’snotvisibletouser.Anyactivitygetsstoppedincasesome
otheractivitytakesplaceofit.Forexample,ifauserwasonscreen1andclickonsomebutton
andmovestoscreen2.InthiscaseActivitydisplayingcontentforscreen1willbestopped.
Everyactivitygetsstoppedbeforedestroyincaseofwhenuserpressbacknavigationbutton.So
Activitywillbeinstoppedstatewhenhiddenorreplacedbyotheractivitiesthathavebeen
launchedorswitchedbyuser.Inthiscaseapplicationwillnotpresentanythingusefultothe
userdirectlyasit’sgoingtostop.
ActivityRestarted:onRestart():
Activityiscalledinrestartstateafterstopstate.Soactivity’sonRestart()functiongetscalled
whenusercomesonscreenorresumetheactivitywhichwasstopped.Inotherwords,when
OperatingSystemstartstheactivityforthefirsttimeonRestart()nevergetscalled.Itgetscalled
onlyincasewhenactivityisresumesafterstoppedstate.
ActivityDestroyed:onDestroy():
Anyactivityisknownasindestroyedstatewhenit’snotinbackground.Therecandifferent
casesatwhattimeactivitygetdestroyed.
Firstisifuserpressedthebacknavigationbuttonthenactivitywillbedestroyedafter
completingthelifecycleofpauseandstop.
Incaseifuserpressthehomebuttonandappmovestobackground.Userisnotusingitnomore
andit’sbeingshowninrecentappslist.Sointhiscaseifsystemrequiredresourcesneedtouse
somewhereelsethenOScandestroytheActivity.
AftertheActivityisdestroyedifuseragainclicktheappicon,inthiscaseactivitywillbe
recreatedandfollowthesamelifecycleagain.AnotherusecaseiswithSplashScreensifthereis
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
21
calltofinish()methodfromonCreate()ofanactivitythenOScandirectlycallonDestroy()with
callingonPause()andonStop().
ActivityLifecycleExample:
InthebelowexamplewehaveusedthebelowJAVAandAndroidtopics:
JAVATopicsUsed:MethodOverriding,staticvariable,package,Inheritance,methodandclass.
AndroidTopicUsed:WehaveusedLogclasswhichisusedtoprintoutmessageinLogcat.One
oftheimportantuseofLogisindebugging.
FirstwewillcreateanewAndroidProjectandnametheactivityasHomeActivity.Inourcasewe
havenamedourAppprojectasActivityLifecycleExample.
WewillinitializeastaticStringvariablewiththenameoftheunderlyingclassusing
getSimpleName()method.InourcaseHOME_ACTIVITY_TAGisthenameoftheStringvariable
whichstoreclassnameHomeActivity.
private
s
tatic
f
inal
S
tring
HOME_ACTIVITY_TAG=
H
omeActivity
.class
.g
etSimpleName
();
NowwewillcreateanewmethodwhichwillprintmessageinLogcat.
privatev
oid
showLog
(S
tring
text
){
L
og
.d
(H
OME_ACTIVITY_TAG
,text
);
}
NowwewilloverrideallactivitylifecyclemethodinAndroidanduseshowLog()methodwhich
wecreatingforprintingmessageinLogcat.
@Override
public
v
oid
onCreate
(B
undle
savedInstanceState
)
{
super
.o
nCreate(s
avedInstanceState);
s
howLog("ActivityCreated"
);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
22
}
@Override
protected
void
onRestart(){
super
.onRestart();
//call torestart
after
onStop
s
howLog("
Activityrestarted" );
}
@Override
protected
void
onStart()
{
super
.onStart();
//soon be visible
s
howLog("
Activitystarted" );
}
@Override
protected
void
onResume()
{
super
.onResume();
//visible
s
howLog("
Activityresumed" );
}
@Override
protected
void
onPause()
{
super
.onPause();
//invisible
s
howLog("
Activitypaused" );
}
@Override
protected
void
onStop
()
{
super
.onStop();
s
howLog("
Activitystopped" );
}
@Override
protected
void
onDestroy(){
super
.onDestroy();
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
23
s
howLog
("
Activity
is
being
destroyed"
);
}
CompleteJAVAcodeofHomeActivity.java:
package
com.a
bhiandroid .activitylifecycleexample;
import
android .o
s.B
undle;
import
android .s
upport .d
esign .widget.FloatingActionButton;
import
android .s
upport .d
esign .widget.Snackbar;
import
android .s
upport .v
7.app
.A
ppCompatActivity;
import
android .s
upport .v
7.widget.T
oolbar;
import
android .u
til .L
og;
import
android .v
iew .V
iew;
import
android .v
iew .M
enu;
import
android .v
iew .M
enuItem;
public
c
lassHomeActivity extends A
ppCompatActivity
{
private
static f
inal S
tring
HOME_ACTIVITY_TAG= H
omeActivity
.class
.g
etSimpleName
();
private
voidshowLog (S
tring text
){
Log
.d(
H
OME_ACTIVITY_TAG ,text
);
}
@Override
public
v
oid
onCreate (B
undle savedInstanceState )
{
super.onCreate (s
avedInstanceState );
s
howLog ("
Activity Created" );
}
@Override
protected
void
onRestart (){
super.onRestart ();//call to
restart after
onStop
s
howLog ("
Activity restarted" );
}
@Override
protected
void
onStart ()
{
super.onStart ();//soon bevisible
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
24
s
howLog
("
Activity
started"
);
}
@Override
protected
v
oid
onResume
()
{
super
.o
nResume
();
//visible
s
howLog
("
Activity
resumed"
);
}
@Override
protected
v
oid
onPause
()
{
super
.o
nPause
();
//invisible
s
howLog
("
Activity
paused"
);
}
@Override
protected
v
oid
onStop
()
{
super
.o
nStop
();
s
howLog
("
Activity
stopped"
);
}
@Override
protected
v
oid
onDestroy
()
{
super
.o
nDestroy
();
s
howLog
("
Activity
is
being
destroyed"
);
}
}
WhencreatinganActivityweneedtoregisterthisinAndroidManifest.xmlfile.Nowquestionis
whyneedtoregister?I t'sactuallybecausemanifestfilehastheinformationwhich
AndroidOSreadveryfirst.Whenregisteringanactivityotherinformationcanalsobedefined
withinmanifestlikeLauncherActivity(Anactivitythatshouldstartwhenuserclickonapp
icon).
HereisdeclarationexampleinAndroidManifest.xmlfile
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
25
<?
xml
version="
1.0"
encoding ="utf-8"
?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package
="
com.abhiandroid.homeactivity">
<
application
a
ndroid :a
llowBackup ="
true"
a
ndroid :i
con="@mipmap/ic_launcher"
a
ndroid :l
abel ="
@string/app_name"
a
ndroid :s
upportsRtl ="
true"
a
ndroid :t
heme ="
@style/AppTheme">
<
activity
a
ndroid :name=".HomeActivity"
a
ndroid :label="@string/app_name"
a
ndroid :theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action
a
ndroid:name ="android.intent.action.MAIN"/
>
<category
a
ndroid:name ="android.intent.category.LAUNCHER"
/
>
</intent-filter>
</activity>
</application>
</manifest>
OutputOfActivityLifecycle:
Whenyouwillruntheaboveprogramyouwillnoticeablankwhitescreenwillopenupin
Emulator.YoumightbewonderingwhereisdefaultHelloworldscreen.Actuallywehave
removeditbyoverridingonCreate()method.Belowistheblankwhitescreenthatwillpopup.
NowgotoLogcatpresentinsideAndroidMonitor:Scrollupandyouwillnoticethreemethods
whichwerecalled:ActivityCreated,ActivitystartedandActivityresumed.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
26
Sothisclears:
firstonCreate()methodwascalledwhenactivitywascreated
secondonStart()methodwascalledwhenactivitystartbecomingvisibletouser
FinallyonResume()methodwascalledwhenactivityisvisibletouserandusercaninteractwith
it
NowpressthebackbuttonontheEmulatorandexittheApp:
GotoLogcatagainandscrolldowntobottom.Youwillsee3moremethodswerecalled:Activity
paused,ActivitystoppedandActivityisbeingdestroyed.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
27
Sothisclears:
❖ onPause()methodwascalledwhenuserresumepreviousactivity
❖ onStop()methodwascalledwhenactivityisnotvisibletouser
❖ LastonDestroy()methodwascalledwhenActivityisnotinbackground
ImportantNote:I ntheaboveexampleonRestart()won’tbecalledbecausetherewasno
situationwhenwecanresumetheonStart()methodagain.Infutureexamplewewillshowyou
onRestart()inactionaswell.
ImportanceOfActivityLifeCycle:
ActivityisthemaincomponentofAndroidApplication,aseveryscreenisanactivitysoto
createanysimpleappfirstwehavetostartwithActivities.Everylifecyclemethodisquite
importanttoimplementaccordingtorequirements,HoweveronCreate(Bundlestate)isalways
neededtoimplementtoshowordisplaysomecontentonscreen.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
28
LinearLayout
Linearlayoutisasimplelayoutusedinandroidforlayoutdesigning.IntheLinearlayoutallthe
elementsaredisplayedinlinearfashionmeansallthechilds/elementsofalinearlayoutare
displayedaccordingtoitsorientation.Thevaluefororientationpropertycanbeeither
horizontalorvertical.
TypesOfLinearLayoutOrientation
Therearetwotypesoflinearlayoutorientation:
1. Vertical
2. Horizontal
Asthenamespecifiedthesetwoorientationsareusedtoarrangetherechildoneaftertheother,
inaline,eitherverticallyorhorizontally.Let’swedescribetheseindetail.
1.Vertical:
Inthisallthechildarearrangedverticallyinalineoneaftertheother.Inbelowcodesnippets
wehavespecifiedorientation“vertical”sothechilds/viewsofthislayoutaredisplayed
vertically.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid
:l
ayout_width="
fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:o
rientation
="
vertical" ><
!--
Vertical
O
rientation
s
et
-
->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
29
<!--
Child
Views(In
this
case
2
Button)
are
here
-->
<
Button
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext="
Button1"
a
ndroid
:i
d
="
@+id/button"
a
ndroid
:b
ackground="
#358a32" /
>
<
Button
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext="
Button2"
a
ndroid
:i
d
="
@+id/button2"
a
ndroid
:b
ackground="
#0058b6" /
>
</LinearLayout>
2.Horizontal:
Inthisallthechildarearrangedhorizontallyinalineoneaftertheother.Inbelowcode
snippetswehavespecifiedorientation“horizontal”sothechilds/viewsofthislayoutare
displayedhorizontally.
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid:l
ayout_width="fill_parent"
a
ndroid:l
ayout_height ="
wrap_content"
a
ndroid:o
rientation="
horizontal" ><
!--
H
orizontal O
rientation
s
et
-
->
<!--
Child
Views(Inthiscase2
Button) are
here
-->
<
Button
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
ext="
Button1"
a
ndroid:i
d
="
@+id/button"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
30
a
ndroid
:b
ackground
="
#358a32"
/
>
<
Button
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext="
Button2"
a
ndroid
:i
d
="
@+id/button2"
a
ndroid
:b
ackground="
#0058b6" /
>
</LinearLayout>
ImportantNote:Allofthelayoutmanagerscanbenested.Thismeansthatyoucanputa
RelativeLayoutorFrameLayoutasachildtoLinearLayout.
MainAttributesInLinearLayout:
Nowlet’s wediscussabouttheattributesthathelpsustoconfigurealinearlayoutanditschild
controls.Someofthemostimportantattributesyouwillusewithlinearlayoutinclude:
1.orientation:T
heorientationattributeusedtosetthechilds/viewshorizontallyor
vertically.InLinearlayoutdefaultorientationisvertical.
Example: Orientationvertical:
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid
:l
ayout_width="fill_parent"
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:o
rientation="
vertical"><
!--V
ertical
O
rientation
s
et
-
->
<!--
PutChild
Viewslike
Buttonhere-->
</LinearLayout>
Example:OrientationHorizontal:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
31
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid
:l
ayout_width="fill_parent"
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:o
rientation="
horizontal"><
!--
H
orizontal
O
rientation
s
et
-
->
<!--
ChildViews
arehere
-->
</LinearLayout>
2.gravity:Thegravityattributeisanoptionalattributewhichisusedtocontrolthe
alignmentofthelayoutlikeleft,right,center,top,bottometc.
Example:Wehavesetgravityrightforlinearlayout.Sothebuttonsgetsalign
fromrightsideinHorizontalorientation.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid
:l
ayout_width ="match_parent"
a
ndroid
:l
ayout_height ="
match_parent"
a
ndroid
:g
ravity="
right"
a
ndroid
:o
rientation ="
horizontal">
<!--Button
ChildView Here--->
<
Button
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext ="
Button2"
a
ndroid
:i
d="
@+id/button2"
a
ndroid
:b
ackground ="#0e7d0d"/
>
<
Button
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext ="
Button1"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
32
a
ndroid
:id
="
@+id/button"
a
ndroid
:background
="
#761212"
/
>
</LinearLayout>
3.layout_weight:Thelayoutweightattributespecifyeachchildcontrol’srelative
importancewithintheparentlinearlayout.
Example:weightpropertyforbuttoninlinearlayout.Inthebelowexampleone
buttonisofweight2andotherisofweight1.
<?
xml
version
="
1.0" encoding ="
utf-8" ?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid
:l
ayout_width ="match_parent"
a
ndroid
:l
ayout_height ="
match_parent"
a
ndroid
:o
rientation ="
horizontal">
<!--Add
ChildView Here--->
<
Button
a
ndroid:layout_width ="
wrap_content"
a
ndroid:layout_height ="wrap_content"
a
ndroid:text="
Weight 2"
a
ndroid:background ="#761212"
a
ndroid:layout_margin ="5dp"
a
ndroid:id
="
@+id/button"
a
ndroid:layout_weight ="2"/>
<
Button
a
ndroid:layout_width ="
wrap_content"
a
ndroid:layout_height ="wrap_content"
a
ndroid:background ="#761212"
a
ndroid:layout_margin ="5dp"
a
ndroid:layout_weight ="1"
a
ndroid:text="
Weight 1"/>
</LinearLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
33
InthelayoutimageyoucannoticeButtonwithweight2getsmoresizerelated
theother.
4.weightSum:weightSumisthesumupofallthechildattributesweight.Thisattributeis
requiredifwedefineweightpropertyofthechilds.
Example:Inthesameaboveexampleofweight,wecandefineweightSumvalue3.
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:w
eightSum="
3"
a
ndroid
:o
rientation="horizontal">
<!--Add
Child
ViewHere--->
</LinearLayout>
ExampleofLinearLayout:
Nowletsdesign2linearlayoutUI.Firstwehavedesignedusingweightattributeandsecond
withoutusingit.Sobelowlayoutoutputwillclearthedifferencebetweenthem:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
34
Example1:FirstwewilldesignAndroidLinearLayoutwithoutusingweightproperty
InthisexamplewehaveusedoneTextViewand4Button.Theorientationissetto
vertical.
Belowisthecodeofactivity_main.xml
<!--Vertical Orientation isset-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid :l
ayout_width ="match_parent"
a
ndroid :l
ayout_height ="
match_parent"
a
ndroid :o
rientation ="
vertical">
<!--
Text DisplayedAt Top-->
<
TextView
a
ndroid :l
ayout_width ="
wrap_content"
a
ndroid :l
ayout_height ="wrap_content"
a
ndroid :t
extAppearance ="?android:attr/textAppearanceLarge"
a
ndroid :t
ext="
Linear Layout (WithoutWeight)"
a
ndroid :i
d
="
@+id/textView"
a
ndroid :l
ayout_gravity ="center_horizontal" /
>
<!--
Button Used-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
35
<
Button
a
ndroid
:l
ayout_width="
fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:t
ext
="
Button1"
a
ndroid
:b
ackground
="
#009300" /
>
<
Button
a
ndroid
:l
ayout_width="
fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:t
ext
="
Button2"
a
ndroid
:b
ackground
="
#e6cf00" /
>
<
Button
a
ndroid
:l
ayout_width="
fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:t
ext
="
Button3"
a
ndroid
:b
ackground
="
#0472f9" /
>
<
Button
a
ndroid
:layout_width="
fill_parent"
a
ndroid
:layout_height="wrap_content"
a
ndroid
:text
="
Button4"
a
ndroid
:background
="
#e100d5" /
>
</LinearLayout>
OutputScreen:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
36
RelativeLayout
TheRelativeLayoutisveryflexiblelayoutusedinandroidforcustomlayoutdesigning.Itgives
ustheflexibilitytopositionourcomponent/viewbasedontherelativeorsiblingcomponent’s
position.Justbecauseitallowsustopositionthecomponentanywherewewantsoitis
consideredasmostflexiblelayout.ForthesamereasonRelativelayoutisthemostusedlayout
aftertheLinearLayoutinAndroid.Itallowitschildviewtopositionrelativetoeachotheror
relativetothecontaineroranothercontainer.
InRelativeLayout,youcanuse“above,below,leftandright”toarrangethecomponent’s
positioninrelationtoothercomponent.F
orexample,inthebelowimageyoucansee
contentisplacedinrelatedtoHeading.
EventhoughAndroidhasdraganddropsystemtoputonecomponentinrelatedtootherinside
relativelayout.ButactuallyinthebackgroundlotsofXMLpropertiesareworkingwhichdoes
thistask.SoAndroiddevelopercandesignUIeitherusingdrag&droporusingXMLcode.
ProfessionaldeveloperusesbothfordesigningUI.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
37
AttributesofRelativelayout:
LetsseedifferentpropertiesofRelativeLayoutwhichwillbeusedwhiledesigningAndroidApp
UI:
1.above:PositionthebottomedgeoftheviewabovethegivenanchorviewIDandmustbea
referenceoftheanotherresourceintheformofid.Example,
android:layout_above=”@+id/textView”.
Forexample,supposeaviewwithidtextview2iswhatwewanttoplaceaboveanotherviewwith
idtextview.Belowisthecodeandlayoutimage.
2.alignBottom:a lignBottomisusedtomakesthebottomedgeoftheviewmatchthebottom
edgeofthegivenanchorviewIDanditmustbeareferencetoanotherresource,intheformof
id.Example:android:layout_alignBottom=”@+id/button1″
InthebelowexamplewehavealignedaviewwithidtextView2Bottomofanotherviewwithid
textView.Belowisthecodedandlayoutimage.
<!--textView2
alignBottomof
textView
-->
<TextView
a
ndroid:l
ayout_width
="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
38
a
ndroid
:l
ayout_height="
wrap_content"
a
ndroid
:t
extAppearance="?android:attr/textAppearanceLarge"
a
ndroid
:l
ayout_centerHorizontal ="
true"
a
ndroid
:i
d
="
@+id/textView2"
a
ndroid
:l
ayout_alignBottom ="
@+id/textView"
a
ndroid
:t
ext="
Text2
alignBottom ofText1"
a
ndroid
:l
ayout_marginBottom ="90dp"
/>
3.alignLeft:a lignLeftisusedtomaketheleftedgeoftheviewmatchtheleftedgeofthe
givenanchorviewIDandmustbeareferencetoanotherresource,intheformofExample:
android:layout_alignLeft=”@+id/button1″.
BelowisthecodeandlayoutimageinwhichwehavealignedaviewwithidtextView2leftof
anotherviewwithidtextView.
<!--textView2alignLeftoftextView
-->
<TextView
a
ndroid:l
ayout_width="wrap_content"
a
ndroid:l
ayout_height="wrap_content"
a
ndroid:t
extAppearance ="
?android:attr/textAppearanceLarge"
a
ndroid:i
d
="
@+id/textView2"
a
ndroid:l
ayout_alignLeft ="
@+id/textView"
a
ndroid:t
ext="
Text2
alignLeft of
Text1"
a
ndroid:l
ayout_below="@+id/textView"
a
ndroid:l
ayout_marginTop ="
20dp"
/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
39
4.alignRight:alignRightpropertyisusedtomaketherightedgeofthisviewmatchtheright
edgeofthegivenanchorviewIDandmustbeareferencetoanotherresource,intheformlike
thisexample:android:layout_alignRight=”@+id/button1″
BelowisthecodeandlayoutimageinwhichwehavealignedaviewwithidtextView2rightof
anotherviewwithidtextView.
<!--textView2alignRightoftextView-->
<TextView
a
ndroid:l
ayout_width="wrap_content"
a
ndroid:l
ayout_height="wrap_content"
a
ndroid:t
extAppearance ="
?android:attr/textAppearanceLarge"
a
ndroid:i
d
="
@+id/textView2"
a
ndroid:l
ayout_alignRight ="@+id/textView"
a
ndroid:t
ext="
Text2
alignRight ofText1"
a
ndroid:l
ayout_below="@+id/textView"
a
ndroid:l
ayout_marginTop ="
20dp"/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
40
5.alignStart:alignStartpropertyisusedtomakesthestartedgeofthisviewmatchthestart
edgeofthegivenanchorviewIDandmustbeareferencetoanotherresource,intheformof
likethisexample:android:layout_alignStart=”@+id/button1″
BelowisthealignStartcodeandlayoutimageinwhichwehavealignedaviewwithidtextView2
startofanotherviewwithidtextView.
<!-- Text2
alignStart-->
<TextView
a
ndroid:l
ayout_width="wrap_content"
a
ndroid:l
ayout_height="wrap_content"
a
ndroid:t
extAppearance ="
?android:attr/textAppearanceLarge"
a
ndroid:i
d
="
@+id/textView2"
a
ndroid:t
ext="
Text2
alignstart
of
Text1"
a
ndroid:l
ayout_alignStart ="
@+id/textView"
/
>
6.alignTop:alignToppropertyisusedtomakesthetopedgeofthisviewmatchthetopedge
ofthegivenanchorviewIDandmustbeareferencetoanotherresource,intheformlikethis
example:android:layout_alignTop=”@+id/button1″.
BelowisthealignTopcodeandlayoutimageinwhichwehavealignedaviewwithidtextView
TopofanotherimagewithidimageView.
<!--textis
align top
on
Image-->
<TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
extAppearance ="?android:attr/textAppearanceLarge"
a
ndroid:i
d
="
@+id/textView"
a
ndroid:l
ayout_alignTop ="
@+id/imageView"
a
ndroid:t
ext="
TextHereisAlignTopon
Image"
/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
41
7.alignParentBottom:I falignParentBottompropertyistrue,makesthebottomedgeofthis
viewmatchthebottomedgeoftheparent.Thevalueofalignparentbottomiseithertrueor
false.Example:android:layout_alignParentBottom=”true”
ImportantNote:alignParentBottomandalignBottomaretwodifferentproperties.In
alignBottomwegivethereferenceofanotherviewintheformofidthattheviewisalignedat
thebottomofreferencedviewbutinalignParentBottomthebottomedgeoftheviewmatches
thebottomedgeoftheparent.
BelowisthealignParentBottomcodeandlayoutimageinwhichtextViewissimplydisplayed
usingthealignParentBottom.
<!--textView
isalignParentBottom -->
<TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
extAppearance ="?android:attr/textAppearanceLarge"
a
ndroid:i
d
="
@+id/textView"
a
ndroid:t
ext="
Text
Here isAlignParentBottom
with
bottom
margin
of
120dp"
a
ndroid:l
ayout_alignParentBottom ="
true"
a
ndroid:l
ayout_alignParentLeft ="
true"
a
ndroid:l
ayout_alignParentStart ="true"
a
ndroid:l
ayout_marginBottom ="
120dp" /
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
42
8.alignParentEnd:IfalignParentEndpropertyistrue,thenitmakestheendedgeofthis
viewmatchtheendedgeoftheparent.ThevalueofalignparentEndiseithertrueorfalse.
Example:android:layout_alignParentEnd=”true”.
ImportantNote:InalignParentEndthebottomedgeoftheviewmatchesthebottomedgeof
theparent.
BelowisthealignParentEndcodeandlayoutimageinwhichtextViewissimplydisplayedon
Imageintheend.
<!-- Textdisplayedin
the endof
parentimage-->
<TextView
a
ndroid :l
ayout_width ="
wrap_content"
a
ndroid :l
ayout_height ="wrap_content"
a
ndroid :t
extAppearance ="?android:attr/textAppearanceLarge"
a
ndroid :i
d
="
@+id/textView"
a
ndroid :t
ext="
Text
inParent End"
a
ndroid :l
ayout_alignBottom ="@+id/imageView"
a
ndroid :l
ayout_alignParentEnd ="
true"
/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
43
9.alignParentLeft:IfalignParentLeftpropertyistrue,makestheleftedgeofthisviewmatch
theleftedgeoftheparent.Thevalueofalignparentleftiseithertrueorfalse.Example:
android:layout_alignParentLeft=”true”.
ImportantNote:alignParentLeftandalignLeftaretwodifferentproperties.InalignLeftwe
givethereferenceofanotherviewintheformofidthattheviewisalignedtotheleftofthe
referencedviewbutinalignParentLefttheleftedgeoftheviewmatchestheleftedgeofthe
parent.
BelowisthealignParentLeftexamplecodeandlayoutimageinwhichtextViewissimply
displayedonparentImageintheleftside.
<!--align
parent left
inAndroid-->
<TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
extAppearance ="?android:attr/textAppearanceLarge"
a
ndroid:i
d
="
@+id/textView"
a
ndroid:t
ext="
Textin
Parent Left"
a
ndroid:l
ayout_alignBottom ="@+id/imageView"
a
ndroid:l
ayout_alignParentLeft ="
true"
/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
44
10.alignParentRight:IfalignParentRightpropertyistrue,thenitmakestherightedgeof
thisviewmatchtherightedgeoftheparent.Thevalueofalignparentrightiseithertrueor
false.Example:android:layout_alignParentRight=”true”.
ImportantNote:alignParentRightandalignRightaretwodifferentproperties.InalignRight
wegivethereferenceofanotherviewintheformofidthattheviewisalignedtotherightofthe
referencedviewbutinalignParentRighttherightedgeoftheviewmatchestherightedgeofthe
parent.
BelowisthealignParentRightexamplecodeandlayoutimageinwhichtextViewissimply
displayedonparentImageintherightside.
<!--alignRightParentExample -->
<TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
extAppearance ="?android:attr/textAppearanceLarge"
a
ndroid:i
d
="
@+id/textView"
a
ndroid:t
ext="
Text
inParent Right"
a
ndroid:l
ayout_alignBottom ="@+id/imageView"
a
ndroid:l
ayout_alignParentRight ="
true"
/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
45
11.alignParentStart:IfalignParentStartistrue,thenitmakesthestartedgeofthisview
matchthestartedgeoftheparent.Thevalueofalignparentstartiseithertrueorfalse.
Example:android:layout_alignParentStart=”true”.
ImportantNote:a lignParentStartandalignStartaretwodifferentproperties,InalignStart
wegivethereferenceofanotherviewintheformofidthattheviewisalignedatthestartof
referencedviewbutinalignParentStartthestartedgeoftheviewmatchesthestartedgeofthe
parent(RelativeLayout).
BelowisthealignParentStartexamplecodeandlayoutimageinwhichtextViewissimply
displayedonparentImageintherightside.
<!--alignParentStartExample -->
<TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
extAppearance ="?android:attr/textAppearanceLarge"
a
ndroid:i
d
="
@+id/textView"
a
ndroid:t
ext="
Text
inParentStart"
a
ndroid:l
ayout_alignTop ="
@+id/imageView"
a
ndroid:l
ayout_alignParentStart ="
true"
/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
46
12.alignParentTop:IfalignParentTopistrue,thenitmakesthetopedgeofthisviewmatch
thetopedgeoftheparent.ThevalueofalignparentTopiseithertrueorfalse.Example:
android:layout_alignParenTop=”true”.
ImportantNote:a lignParentTopandalignToparetwodifferentproperties,InalignTopwe
givethereferenceofanotherviewintheformofidthattheviewisalignedtothetopofthe
referencedviewbutinalignParentTopthetopedgeoftheviewmatchesthetopedgeofthe
parent(RelativeLayout).
BelowistheexamplecodeofalignParentToppropertyandalsolayoutimage.
<!--alignParentTopexample -->
<TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
ext
="Text1align parent top"
a
ndroid:l
ayout_alignParentTop ="
true"
a
ndroid:l
ayout_margin ="20dp"
a
ndroid:t
extSize="
20sp"
a
ndroid:t
extColor="#000"/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
47
13.centerInParent:Ifcenterinparentistrue,makestheviewinthecenterofthescreen
verticallyandhorizontally.Thevalueofcenterinparentiseithertrueorfalse.Example:
android:layout_centerInParent=”true”.
BelowistheexamplecodeofcenterInParentpropertyandalsolayoutimage.
<!--centerInParentexample -->
<TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
ext
="Text1center in
parent"
a
ndroid:l
ayout_centerInParent ="
true"
a
ndroid:t
extSize="
20sp"
a
ndroid:t
extColor="#000"
/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
48
14.centerHorizontal:IfcenterHorizontalpropertyistrue,makestheviewhorizontally
center.ThevalueofcenterHorizontaliseithertrueorfalse.Example:
android:layout_centerHorizontal=”true”.
BelowistheexamplecodeofcenterHorizontalpropertyandalsolayoutimage.
<!--centerHorizontal example-->
<TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
ext
="Text1centerHorizontal"
a
ndroid:l
ayout_centerHorizontal ="
true"
a
ndroid:t
extSize="
20sp"
a
ndroid:t
extColor="#000"
/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
49
15.centerVertical:IfcenterVerticalpropertyistrue,maketheviewverticallycenter.The
valueofalignparentbottomiseithertrueorfalse.Example:
android:layout_centerVertical=”true”.
BelowistheexamplecodeofcenterVerticalpropertyandalsolayoutimage.
<!--centerVerticalexample -->
<TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:t
ext
="Text1center vertical"
a
ndroid:l
ayout_centerVertical ="
true"
a
ndroid:t
extSize="
20sp"
a
ndroid:t
extColor="#000"
/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
50
RelativeLayoutExamplesWithCodeAndExplanation:
Example1:HerewearedesigningasimpleloginscreeninAndroidStudiousingRelative
Layout.Belowisthefinaloutput:
Belowisthecodeofactivity_main.xmlfordesigningUIwithexplanationincludedinit:
<?
xml
version
="1.0"
encoding ="
utf-8"?>
<!--RelativeLayoutIs
Used-->
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent">
<!--Text
View
forDisplaying SIGN
INText
At
Top
of
UI-->
<
TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
51
a
ndroid
:t
extAppearance="?android:attr/textAppearanceLarge"
a
ndroid
:t
ext="
SIGN
IN"
a
ndroid
:i
d
="
@+id/textView3"
a
ndroid
:l
ayout_alignParentTop ="
true"
a
ndroid
:l
ayout_centerHorizontal ="
true"
/
>
<!--Text
View
for
Displaying
Username-->
<
TextView
a
ndroid
:i
d
="
@+id/userName"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_marginLeft ="
@dimen/activity_horizontal_margin"
a
ndroid
:l
ayout_marginTop ="110dp"
a
ndroid
:t
ext="
UserName:"
a
ndroid
:t
extColor="#000000"
a
ndroid
:t
extSize="
20sp" /
>
<!--Text
View
for
Displaying
Password-->
<
TextView
a
ndroid
:i
d
="
@+id/password"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_below ="
@+id/userName"
a
ndroid
:l
ayout_margin ="@dimen/activity_horizontal_margin"
a
ndroid
:t
ext="
Password:"
a
ndroid
:t
extColor="#000000"
a
ndroid
:t
extSize="
20sp" /
>
<!--Edit
Text
for
Filling
Username-->
<
EditText
a
ndroid
:i
d
="
@+id/edt_userName"
a
ndroid
:l
ayout_width ="
fill_parent"
a
ndroid
:l
ayout_height ="40dp"
a
ndroid
:l
ayout_marginLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:l
ayout_marginTop ="
100dp"
a
ndroid
:l
ayout_toRightOf ="
@+id/userName"
a
ndroid
:h
int="
User
Name" /
>
<!--Edit
Text
for
Filling
Password-->
<
EditText
a
ndroid
:l
ayout_width
="
fill_parent"
a
ndroid
:l
ayout_height
="40dp"
a
ndroid
:l
ayout_below
="
@+id/edt_userName"
a
ndroid
:l
ayout_centerVertical ="
true"
a
ndroid
:l
ayout_toRightOf="@+id/password"
a
ndroid
:h
int
="
Password"/
>
<!--Button
for
Clicking
after
filling
details-->
<
Button
a
ndroid
:i
d
="
@+id/btnLogin"
a
ndroid
:l
ayout_width
="
wrap_content"
a
ndroid
:l
ayout_height
="wrap_content"
a
ndroid
:l
ayout_below
="
@+id/password"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
52
a
ndroid
:l
ayout_centerHorizontal="true"
a
ndroid
:l
ayout_marginTop="
20dp"
a
ndroid
:b
ackground
="#03B424"
a
ndroid
:t
ext
="
Login"
a
ndroid
:t
extColor
="
#ffffff"
a
ndroid
:t
extStyle
="
bold"/
>
</RelativeLayout>
Output:
DifferencebetweenLinearAndRelativeLayout:
RELATIVELAYOUT:
● Everyelementofrelativelayoutarrangesitselftotheotherelementoraparentelement.
● Itishelpfulwhileaddingviewsonenexttootheretc
● InarelativelayoutyoucangiveeachchildaLayoutPropertythatspecifiesexactly
whereitshouldgoinrelativetotheparentorrelativetootherchildren.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
53
● Viewscanbelayeredontopofeachother.
LINEARLAYOUT:
● Inalinearlayout,likethenamesuggests,alltheelementsaredisplayedinalinear
fashioneitherverticallyorhorizontally.
● EitherHorizontallyorVerticallythisbehaviorissetinandroid:orientationwhichisan
propertyofthenodeLinearLayout.
android
:o
rientation
="
horizontal"
o
r
android
:o
rientation
="
vertical"
● Linearlayoutsputeverychild,oneaftertheother,inaline,eitherhorizontallyor
vertically.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
54
TableLayout
InAndroid,TableLayoutisusedtoarrangethegroupofviewsintorowsandcolumns.Table
Layoutcontainersdonotdisplayaborderlinefortheircolumns,rowsorcells.ATablewillhave
asmanycolumnsastherowwiththemostcells.
Atablecanalsoleavethecellsemptybutcellscan’tspanthecolumnsastheycanin
HTML(Hypertextmarkuplanguage).
ImportantPointsAboutTableLayoutInAndroid:
Forbuildingarowinatablewewillusethe<TableRow>element.Tablerowobjectsarethe
childviewsofatablelayout.
Eachrowofthetablehaszeroormorecellsandeachcellcanholdonlyoneviewobjectlike
ImageView,TextVieworanyotherview.
Totalwidthofatableisdefinedbyitsparentcontainer
Columncanbebothstretchableandshrinkable.Ifshrinkablethenthewidthofcolumncanbe
shrunktofitthetableintoitsparentobjectandifstretchablethenitcanexpandinwidthtofit
anyextraspaceavailable.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
55
ImportantNote:Wecannotspecifythewidthofthechildren’softheTablelayout.Here,
widthalwaysmatchparentwidth.However,theheightattributecanbedefinedbyachild;
defaultvalueofheightattributeiswrapcontent.
BasicTableLayoutcodeinXML:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid:l
ayout_width ="
match_parent"
a
ndroid:l
ayout_height ="match_parent"
a
ndroid:c
ollapseColumns ="
0"><
!--
collapse the
first
column
of
the
table
row
-->
<!--
first rowof
thetablelayout-->
<
TableRow
a
ndroid :id
="
@+id/row1"
a
ndroid :layout_width ="fill_parent"
a
ndroid :layout_height ="
wrap_content">
<!--
Addelements/columns in
the first
row-->
</TableRow>
</TableLayout>
AttributesofTableLayoutinAndroid:
Nowlet’swediscusssomeimportantattributesthathelpustoconfigureatablelayoutinXML
file(layout).
1.id:idattributeisusedtouniquelyidentifyaTableLayout.
<TableLayout
android
:i
d
="
@+id/simpleTableLayout"
android
:l
ayout_width
="
match_parent"
android
:l
ayout_height
="match_parent/>
2.stretchColumns:S tretchcolumnattributeisusedinTableLayouttochangethedefault
widthofacolumnwhichissetequaltothewidthofthewidestcolumnbutwecanalsostretch
thecolumnstotakeupavailablefreespacebyusingthisattribute.Thevaluethatassignedto
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
56
thisattributecanbeasinglecolumnnumberoracommadelimitedlistofcolumnnumbers(1,
2,3…n).
Ifthevalueis1thenthesecondcolumnisstretchedtotakeupanyavailablespaceintherow,
becauseofthecolumnnumbersarestartedfrom0.
Ifthevalueis0,1thenboththefirstandsecondcolumnsoftablearestretchedtotakeupthe
availablespaceintherow.
Ifthevalueis‘*’thenallthecolumnsarestretchedtotakeuptheavailablespace.
Belowistheexamplecodeofstretchcolumnattributeoftablelayoutwithexplanationincluded
inwhichwestretchthefirstcolumnoflayout.
<?
xml
version
="1.0"encoding="utf-8" ?>
<
TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid:i
d="
@+id/simpleTableLayout"
a
ndroid:l
ayout_width ="
match_parent"
a
ndroid:l
ayout_height ="match_parent"
a
ndroid:s
tretchColumns ="1"><!--stretch the
second
column
of
the
layout
-->
<!--
firstrow of
the table layout-->
<
TableRow
a
ndroid :id
="
@+id/firstRow"
a
ndroid :layout_width ="fill_parent"
a
ndroid :layout_height ="
wrap_content">
<!-- first element ofthe row-->
<
TextView
a
ndroid :i
d
="
@+id/simpleTextView"
a
ndroid :l
ayout_width ="
wrap_content"
a
ndroid :l
ayout_height ="wrap_content"
a
ndroid :b
ackground ="#b0b0b0"
a
ndroid :p
adding ="
18dip"
a
ndroid :t
ext="
Text 1"
a
ndroid :t
extColor ="
#000"
a
ndroid :t
extSize ="12dp" />
<
TextView
a
ndroid :i
d
="
@+id/simpleTextView"
a
ndroid :l
ayout_width ="
wrap_content"
a
ndroid :l
ayout_height ="wrap_content"
a
ndroid :b
ackground ="#FF0000"
a
ndroid :p
adding ="
18dip"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
57
a
ndroid
:t
ext
="
Text2"
a
ndroid
:t
extColor
="#000"
a
ndroid
:t
extSize
="
14dp"/
>
</TableRow>
</TableLayout>
3.shrinkColumns:S hrinkcolumnattributeisusedtoshrinkorreducethewidthofthe
column‘s.Wecanspecifyeitherasinglecolumnoracommadelimitedlistofcolumnnumbers
forthisattribute.Thecontentinthespecifiedcolumnsword-wrapstoreducetheirwidth.
Ifthevalueis0thenthefirstcolumn’swidthshrinksorreducesbywordwrappingitscontent.
Ifthevalueis0,1thenbothfirstandsecondcolumnsareshrinksorreducedbywordwrapping
itscontent.
Ifthevalueis‘*’thenthecontentofallcolumnsiswordwrappedtoshrinktheirwidths.
Belowistheexamplecodeofshrinkcolumnattributeoftablelayoutwithexplanationincluded
inwhichweshrinkthefirstcolumnoflayout.
<?
xml
version="1.0"
encoding="
utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid:l
ayout_width ="
match_parent"
a
ndroid:l
ayout_height ="match_parent"
a
ndroid:s
hrinkColumns ="0"
><!--
shrink the
first
column
of
the
layout
-->
<!--
firstrowof
thetablelayout-->
<
TableRow
a
ndroid :i
d
="
@+id/firstRow"
a
ndroid :l
ayout_width ="
fill_parent"
a
ndroid :l
ayout_height ="wrap_content">
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
58
!--
< first
elementofthe first row-->
<
TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:b
ackground ="#b0b0b0"
a
ndroid:p
adding="
18dip"
a
ndroid:t
ext
="Shrink Column Example"
a
ndroid:t
extColor ="
#000"
a
ndroid:t
extSize="18dp" />
</TableRow>
</TableLayout>
4.collapseColumns:collapsecolumnsattributeisusedtocollapseorinvisiblethecolumn’s
ofatablelayout.Thesecolumnsarethepartofthetableinformationbutareinvisible.
Ifthevaluesis0thenthefirstcolumnappearscollapsed,i.eitisthepartoftablebutitis
invisible.
Belowistheexamplecodeofcollapsecolumnswithexplanationincludedinwhichwecollapse
thefirstcolumnoftablemeansfirstcolumnisanpartoftablebutitisinvisiblesoyoucansee
onlythesecondcolumninscreenshot.
<?
xml
version="1.0"
encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid:l
ayout_width ="
match_parent"
a
ndroid:l
ayout_height ="match_parent"
a
ndroid:c
ollapseColumns ="
0"><
!--
collapse the
first
columnof
thetable
row
-->
<!--
firstrowof
thetablelayout-->
<
TableRow
a
ndroid :i
d
="
@+id/simpleTableLayout"
a
ndroid :l
ayout_width ="fill_parent"
a
ndroid :l
ayout_height ="
wrap_content">
<!--
firstelementoftherow
that isthe
part
oftable
butit
is
invisible-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
59
<
TextView
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:b
ackground ="#b0b0b0"
a
ndroid
:p
adding="
18dip"
a
ndroid
:t
ext
="Columns 1"
a
ndroid
:t
extColor ="
#000"
a
ndroid
:t
extSize="18dp" />
!--
< second
elementof therow that
is
shown
in
the
screenshot-->
<
TextView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:b
ackground ="#b0b0b0"
a
ndroid:p
adding="
18dip"
a
ndroid:t
ext
="Columns 2"
a
ndroid:t
extColor ="
#000"
a
ndroid:t
extSize="18dp" />
</TableRow>
</TableLayout>
TableLayoutExampleInAndroidStudio:
BelowisanexampleofTablelayoutinAndroidwherewedisplayaloginformwithtwofields
usernameandpasswordandoneloginbuttonandwheneverauserclickonthatbuttona
messagewillbedisplayedbyusingaToast.
Belowyoucandownloadprojectcode,seefinaloutputandstepbystepexplanationofthe
example:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
60
Step1:C
reateanewprojectandnameitTableLayoutExample
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthisstepweopenanxmlfile(activity_main.xml)andaddthecodefordisplayingusername
andpasswordfieldsbyusingtextviewandedittextwithoneloginbutton.
<TableLayoutxmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:b
ackground="
#000"
a
ndroid
:o
rientation="vertical"
a
ndroid
:s
tretchColumns ="1">
<TableRow
a
ndroid:padding ="5dip">
<
TextView
android
:l
ayout_height ="
wrap_content"
android
:l
ayout_marginBottom ="20dp"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
61
a
ndroid
:l
ayout_span ="
2"
a
ndroid
:g
ravity="
center_horizontal"
a
ndroid
:t
ext
="@string/loginForm"
a
ndroid
:t
extColor ="
#0ff"
a
ndroid
:t
extSize="25sp"
a
ndroid
:t
extStyle ="
bold"/>
</TableRow>
<TableRow>
<
TextView
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:l
ayout_column ="
0"
a
ndroid
:l
ayout_marginLeft ="
10dp"
a
ndroid
:t
ext
="@string/userName"
a
ndroid
:t
extColor="#fff"
a
ndroid
:t
extSize="
16sp" /
>
<
EditText
a
ndroid
:i
d
="
@+id/userName"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_column ="1"
a
ndroid
:l
ayout_marginLeft ="10dp"
a
ndroid
:b
ackground ="#fff"
a
ndroid
:h
int="
@string/userName"
a
ndroid
:p
adding="
5dp"
a
ndroid
:t
extColor ="
#000" /
>
</TableRow>
<TableRow>
<
TextView
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:l
ayout_column ="
0"
a
ndroid
:l
ayout_marginLeft ="
10dp"
a
ndroid
:l
ayout_marginTop ="20dp"
a
ndroid
:t
ext
="@string/password"
a
ndroid
:t
extColor="#fff"
a
ndroid
:t
extSize="
16sp" /
>
<
EditText
a
ndroid
:i
d
="
@+id/password"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_column ="1"
a
ndroid
:l
ayout_marginLeft ="10dp"
a
ndroid
:l
ayout_marginTop ="
20dp"
a
ndroid
:b
ackground ="#fff"
a
ndroid
:h
int="
@string/password"
a
ndroid
:p
adding="
5dp"
a
ndroid
:t
extColor ="
#000" /
>
</TableRow>
<TableRow
a
ndroid:layout_marginTop
="
20dp">
<
Button
a
ndroid
:i
d
="
@+id/loginBtn"
a
ndroid
:l
ayout_height
="
wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
62
a
ndroid
:l
ayout_gravity ="
center"
a
ndroid
:l
ayout_span ="
2"
a
ndroid
:b
ackground="#0ff"
a
ndroid
:t
ext
="@string/login"
a
ndroid
:t
extColor="#000"
a
ndroid
:t
extSize="
20sp"
a
ndroid
:t
extStyle="bold"/>
</TableRow>
</TableLayout>
Step3:O
pensrc->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodetoinitiatetheedittextandbuttonandthen
performclickeventonbuttonanddisplaythemessagebyusingaToast.
packageexample .abhiandriod .t
ablelayoutexample;
import
android .s
upport .v7
.app
.AppCompatActivity;
import
android .o
s.B
undle;
import
android .v
iew .M
enu;
import
android .v
iew .M
enuItem;
import
android .v
iew .V
iew;
import
android .w
idget .Button;
import
android .w
idget .Toast;
publicc
lassMainActivity extends A
ppCompatActivity {
@Override
protected
voidonCreate (B
undle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .a
ctivity_main );
//
initiate a button
Button
loginButton= (Button )
findViewById (R
.i
d
.loginBtn
);
//
perform click event onthe button
l
oginButton .s
etOnClickListener (new V
iew.O
nClickListener ()
{
@Override
public void
onClick (View
v)
{
Toast
.makeText (g
etApplicationContext (),"
Hello
AbhiAndroid..!!!"
,
Toast
.LENGTH_LONG ).
show (); /
/ display a
toast message
}
});
}
}
Step4:O
penres->values->strings.xml
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
63
Inthisstepweopenstringfilewhichisusedtostorestringdataoftheapp.
<resources>
<string
n
ame
="app_name"
>T
ableLayoutExample </string>
<string
n
ame
="hello_world">H
elloworld!
</string>
<string
n
ame
="action_settings">S
ettings</string>
<string
n
ame
="loginForm"
>Login
Form</string>
<string
n
ame
="userName"
>U
serName </string>
<string
n
ame
="password"
>P
assword </string>
<string
n
ame
="login"
>L
ogIn</string>
</resources>
Output:
NowruntheAppandyouwillseetheLoginformUIwhichwedesignedinTableLayout.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
64
FrameLayout
FrameLayoutisoneofthesimplestlayouttoorganizeviewcontrols.Theyaredesignedtoblock
anareaonthescreen.FrameLayoutshouldbeusedtoholdchildview,becauseitcanbe
difficulttodisplaysingleviewsataspecificareaonthescreenwithoutoverlappingeachother.
WecanaddmultiplechildrentoaFrameLayoutandcontroltheirpositionbyassigninggravity
toeachchild,usingtheandroid:layout_gravityattribute.
AttributesofFrameLayout:
LetsseedifferentpropertiesofFrameLayoutwhichwillbeusedwhiledesigningAndroidApp
UI:
1.android:id
ThisistheuniqueidwhichidentifiesthelayoutintheR.javafile.
Belowistheidattribute’sexamplewithexplanationincludedinwhichwedefinetheidfor
FrameLayout.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
65
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android
:i
d
="
@+id/frameLayout"
android
:l
ayout_width
="
fill_parent"
android
:l
ayout_height
="fill_parent"
/>
2.android:foreground
Foregrounddefinesthedrawabletodrawoverthecontentandthismaybeacolorvalue.
Possiblecolorvaluescanbeintheformof“#rgb”,“#argb”,“#rrggbb”,or“#aarrggbb”.Thisall
aredifferentcolorcodemodelused.
Example:InBelowexampleofforegroundwesetthegreencolorforforegroundofframeLayout
sotheImageViewandotherchildviewsofthislayoutwillnotbeshown.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android
:i
d="
@+id/framelayout"
android
:l
ayout_width ="
match_parent"
android
:l
ayout_height ="match_parent"
android
:l
ayout_gravity ="center"
android
:f
oregroundGravity ="
fill"
android
:f
oreground ="#0f0"><!-- foreground colorfor
aF
rameLayout-->
<LinearLayout
android
:o
rientation ="vertical"
android
:l
ayout_width ="
wrap_content"
android
:l
ayout_height ="wrap_content"
android
:l
ayout_centerInParent ="
true"
>
<!--
Imageview willnotbeshown because
offoreground
color
whichisdrawn
over
it-->
<ImageView
android
:l
ayout_width ="
200dp"
android
:l
ayout_height ="200dp"
android
:l
ayout_marginBottom ="10dp"
android
:s
rc="@mipmap/ic_launcher"
android
:s
caleType ="
centerCrop"
/>
<!--Textview will
not be
shown becauseofforeground
color
isdrawnover
it-->
<TextView
android
:l
ayout_width ="
match_parent"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
66
android
:l
ayout_height="
wrap_content"
android
:g
ravity="
center_horizontal"
android
:t
ext
="
abhiAndroid"/>
</LinearLayout>
</FrameLayout>
ImportantNote:Onapplyingandroid:foregroudfeature,alltheviewstakeninthe
framelayoutwillgoestothebackgroundandtheframelayoutcomesintheforegroundi.e.over
theviews.Wecansetthe@drawable/image_nameorthecolorintheforeground.
3.android:foregroundGravity
Thisdefinesthegravitytoapplytotheforegrounddrawable.Defaultvalueofgravityisfill.We
cansetvaluesintheformof“top”,”center_vertical”,”fill_vertical”,”center_horizontal”,
”fill_horizontal”,”center”, ”fill”,”clip_vertical”,”clip_horizontal”,”bottom”,”left”or”right”.
Itisusedtosetthegravityof foreground.Wecanalsosetmultiplevaluesbyusing“|”.Ex:
fill_horizontal|top.Boththefill_horizontalandtopgravityaresettoframelayout.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
67
IntheabovesameexampleofforegroundwealsosettheforegroundGravityofFrameLayoutto
fill.
4.android:visibility
Thisdeterminewhethertomaketheviewvisible,invisibleorgone.
visible–
theviewispresentandalsovisible
invisible–
Theviewispresentbutnotvisible
gone–Theviewisneitherpresentnorvisible
5.android:measureAllChildren
Thisdetermineswhethertomeasureallchildrenincludinggonestatevisibilityorjustthose
whichareinthevisibleorinvisiblestateofmeasuringvisibility.Thedefaultvalueof
measureallchildrenisfalse.Wecansetvaluesintheformof Boolean i.e.“true”OR“false”.
Thismayalsobeareferencetoaresource(intheform“@[package:]type:name“)ortheme
attribute(intheform“?[package:][type:]name“)containingavalueofthistype.
ImportantNote:I fmeasureallchildrenissettruethenitwillshowactualwidthandheightof
framelayouteveniftheviewsvisibilityisingonestate.
Theabovepropertyhasbeenexplainedbelow:
ExampleofFramelayouthavingmeasureAllChildrenattribute:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
68
InthebelowcodetheImageViewvisibilityissetgoneandmeasureAllChildrenissettrue.The
outputwillshowactualheightandwidththeFrameLayoutdespitevisibilityissetgone.We
haveusedToasttodisplaytheheightandwidth:
BelowistheCodeofactivity_main.xml
ImportantNote:MakesureyouhaveimageinDrawablefolder.Inourcasewehaveused
ic_launcherimagewhichweaddedinDrawable.
<?
xml version
="1.0"
encoding ="
utf-8" ?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:i
d
="@+id/frame"
android
:o
rientation="
vertical"
android:l
ayout_width
="wrap_content"
android
:l
ayout_height ="
wrap_content"
android
:m
easureAllChildren ="
true"
>
<ImageView
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:v
isibility="gone"
a
ndroid:s
rc
="
@drawable/ic_launcher" />
</FrameLayout>
BelowisthecodeofMainActivity.java.H
erewehaveusedToasttodisplayheightandwidth
onscreen.
publicc
lass M
ainActivity extends A
ctivity
{
@Override
protected
v
oid
onCreate (BundlesavedInstanceState ){
super
.o
nCreate(savedInstanceState );
s
etContentView (R.
layout.d
emo );
FrameLayout
frame=(FrameLayout )findViewById(R
.i
d.f
rame
);
f
rame .m
easure(V
iew .M
easureSpec .UNSPECIFIED,V
iew .M
easureSpec
.U
NSPECIFIED
);
int
width=frame.getMeasuredWidth ();
int
height=frame .g
etMeasuredHeight ();
Toast
.m
akeText(getApplicationContext (),
"width=" +w
idth
+"
height=" +height,T
oast.L
ENGTH_SHORT ).show();
}
}
WhenyouruntheAppinEmulatoryouwillseethebelowoutput:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
69
ExplanationofExample:Itmeasuresallthechildreninthelayout.Forex:IfwesetVisiblity
ofanviewbegoneandsetmeasuresAllChildrenpropertytobetrue,thenalsoitwillalsocount
tothatviewwhichisnotvisible,butifwesetthemeasuresAllChildrenpropertytobefalse,
thenitwillnotcounttothatviewwhichisgone.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
70
ThingsToDoYourself:T
rychangingmeasuresAllChildrenvaluetofalseandruntheAppin
Emulator.Youwillseetheoutputshows0widthandheightofFrameLayout.
ExampleOfFrameLayoutinAndroidStudio:
Example1:FrameLayoutusinglayoutgravity.Herewewillputtextviewatdifferentposition
inFrameLayout.Belowisthecodeandfinaloutput:
Step1:CreateanewprojectinAndroidStudioandnameitFrameTesting.(SelectFile->New
->NewProject.Filltheformsandclick“Finish”button)
Step2:NowOpenres->layout->activity_main.xmlandaddthefollowingcode.Hereweare
puttingdifferentTextViewinFrameLayout.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
71
<?
xmlversion
="1.0"
encoding ="utf-8" ?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid:l
ayout_height ="match_parent"
a
ndroid:l
ayout_width ="
match_parent"
>
<
TextView android:text="LeftTop"
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:l
ayout_height ="wrap_content" /
>
<
TextView android:layout_height="wrap_content"
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:t
ext="
RightTop"
a
ndroid:l
ayout_gravity ="top|right" />
<
TextView android:layout_height="wrap_content"
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:t
ext="
CentreTop"
a
ndroid:l
ayout_gravity ="top|center_horizontal" /
>
<
TextView android:text="Left"
a
ndroid:l
ayout_gravity ="left|center_vertical"
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:l
ayout_height ="wrap_content" /
>
<
TextView android:layout_height="wrap_content"
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:t
ext="
Right"
a
ndroid:l
ayout_gravity ="right|center_vertical" /
>
<
TextView android:layout_height="wrap_content"
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:t
ext="
Centre"
a
ndroid:l
ayout_gravity ="center" />
<
TextView android:text="LeftBottom"
a
ndroid:l
ayout_gravity ="left|bottom"
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:l
ayout_height ="wrap_content" /
>
<
TextView android:layout_height="wrap_content"
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:t
ext="
RightBottom"
a
ndroid:l
ayout_gravity ="right|bottom" />
<
TextView android:layout_height="wrap_content"
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:t
ext="
CenterBottom"
a
ndroid:l
ayout_gravity ="center|bottom" /
>
</FrameLayout>
Step3:L
ettheMainActivity.javahasdefaultAndroidcodeoraddthebelowcode:
package
abhiandroid .c
om
.frametesting;
import
android .s
upport.v
7.app
.A
ppCompatActivity;
import
android .o
s
.B
undle;
public
c
lassM
ainActivity extends
A
ppCompatActivity
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
72
Override
@
protected
v
oid
onCreate(B
undle
savedInstanceState
)
{
super
.o
nCreate
(s
avedInstanceState);
s
etContentView
(R
.l
ayout
.a
ctivity_main
);
}
}
Output:
RuntheAppinEmulator,youwillseeTextviewpositionedatvariouspositioninFrameLayout
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
73
Adapter
InAndroid,AdapterisabridgebetweenUIcomponentanddatasourcethathelpsustofilldata
inUIcomponent.ItholdsthedataandsendthedatatoanAdapterviewthenviewcantakesthe
datafromtheadapterviewandshowsthedataondifferentviewslikeasListView,GridView,
Spinneretc.FormorecustomizationinViewsweusesthebaseadapterorcustomadapters.
TofilldatainalistoragridweneedtoimplementAdapter.Adaptersactslikeabridgebetween
UIcomponentanddatasource.Heredatasourceisthesourcefromwherewegetthedataand
UIcomponentsarelistorgriditemsinwhichwewanttodisplaythatdata.
BelowisaconceptualdiagramofAdapter:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
74
AdaptersInAndroid:
TherearethesomecommonlyusedAdapterinAndroidusedtofillthedataintheUI
components.
BaseAdapter–Itisparentadapterforallotheradapters
ArrayAdapter–Itisusedwheneverwehavealistofsingleitemswhichisbackedbyanarray
CustomArrayAdapter–Itisusedwheneverweneedtodisplayacustomlist
SimpleAdapter–I tisaneasyadaptertomapstaticdatatoviewsdefinedinyourXMLfile
CustomSimpleAdapter–Itisusedwheneverweneedtodisplayacustomizedlistandneededto
accessthechilditemsofthelistorgrid
NowwedescribeeachAdaptersonebyoneindetail:
1.BaseAdapterInAndroid:
BaseAdapterisacommonbaseclassofageneralimplementationofanAdapterthatcanbe
usedinListView,GridView,Spinneretc.WheneverweneedacustomizedlistinaListViewor
customizedgridsinaGridViewwecreateourownadapterandextendbaseadapterinthat.Base
AdaptercanbeextendedtocreateacustomAdapterfordisplayingacustomlistitem.
ArrayAdapterisalsoanimplementationofBaseAdapter.
CustomAdaptercodewhichextendstheBaseAdapterinthat:
public
c
lass CustomAdapter extends
B
aseAdapter
{
@Override
public
i
nt
getCount ()
{
return
0
;
}
@Override
public
O
bject
getItem
(int
i)
{
return
n
ull;
}
@Override
public
l
onggetItemId(int
i)
{
return
0
;
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
75
@Override
public
V
iew
getView
(i
nt
i,V
iew
view
,V
iewGroup
viewGroup
)
{
return
n
ull;
}
InabovecodesnippetweseetheoverridedfunctionsofBaseAdapterwhichareusedtosetthe
datainalist,gridoraspinner.ThesefunctionsaredescribedinBaseAdaptertutorialwith
example.
2.ArrayAdapterInAndroid:
WheneverwehavealistofsingleitemswhichisbackedbyanArray,wecanuseArrayAdapter.
Forinstance,listofphonecontacts,countriesornames.
HereishowandroidArrayAdapterlooks:
ArrayAdapter
(Context
context
,i
nt
resource
,i
nt
textViewResourceId
,
T[]
objects)
TheabovefunctionaredescribedinArrayAdaptertutorialwithexample.
3.CustomArrayAdapterInAndroid:
ArrayAdapterisalsoanimplementationofBaseAdapter,soifwewantmorecustomizationthen
wecancreateacustomadapterandextendArrayAdapterinthat.Sincearrayadapterisan
implementationofBaseAdapter,sowecanoverrideallthefunction’sofBaseAdapterinour
customadapter.
BelowCustomadapterclassMyAdapterextendsArrayAdapterinthat:
publicc
lassM
yAdapter e
xtends A
rrayAdapter
{
publicM
yAdapter (C
ontext context,i
nt
resource ,i
nt
textViewResourceId,List
objects
)
{
super
(c
ontext ,
resource , textViewResourceId ,
objects );
}
@Override
publici
nt
getCount ()
{
returns
uper.g
etCount();
}
@Override
publicV
iew
getView(i
ntposition ,V
iew
convertView,ViewGroup
parent
)
{
returns
uper.g
etView(p
osition ,
convertView ,
parent);
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
76
}
ThesefunctionsaredescribedinCustomArrayAdaptertutorialwithexample.
4.SimpleAdapterInAndroid:
InAndroid SimpleAdapterisaneasyAdaptertomapstaticdatatoviewsdefinedinanXML
file(layout).InAndroidwecanspecifythedatabackingtoalistasanArrayListofMaps(i.e.
hashmaporother).EachentryinaArrayListiscorrespondingtoonerowofalist.
TheMapcontainsthedataforeachrow.HerewealsospecifyanXMLfile(customlistitemsfile)
thatdefinestheviewswhichisusedtodisplaytherow,andamappingfromkeysintheMapto
specificviews.
Wheneverwehavetocreateacustomlistweneedtoimplementcustomadapter.Aswediscuss
earlierArrayAdapterisusedwhenwehavealistofsingleitem’sbackedbyanArray.Soifwe
needmorecustomizationinaListVieworaGridViewweneedtoimplementsimpleadapter.
SimpleAdaptercodeinAndroid:
SimpleAdapter(
C
ontext
context
,L
ist
<?
e
xtends
M
ap
<S
tring
,?
>>
data
,i
nt
resource
,S
tring
[]
from
,i
nt
[]
to)
TheaboveparametersofasimpleAdapterisdescribedinSimpleAdaptertutorialwithexample.
5.CustomSimpleAdapterInAndroid:
Wheneverwehavetocreateacustomlistweneedtoimplementcustomadapter.Aswediscuss
earlierArrayAdapterisusedwhenwehavealistofsingleitem’sbackedbyanArray.Soifwe
needcustomizationinaListVieworaGridViewweneedtoimplementsimpleAdapterbutwhen
weneedmorecustomizationinlistorgriditemswherewehavemanyview’sinalistitemand
thenwehavetoperformanyeventlikeclickoranyothereventtoaparticularviewthenwe
needtoimplementacustomadapterwhofulfillsourrequirement’sandquiteeasytobe
implemented.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
77
BaseAdapteristheparentadapterforallotheradapterssoifweextendsaSimpleAdapterthen
wecanalsooverridethebaseadapter’sfunctioninthatclass.
ImportantNote:Wecan’tperformeventslikeclickandothereventonchilditemofalistor
gridbutifwehavesomerequirementstodothatthenwecancreateourowncustomadapter
andextendsthesimpleadapterinthat.
CustomAdapterextendsSimpleAdapterinthat:
publicc
lass C
ustomAdapter extendsSimpleAdapter
{
publicC
ustomAdapter (Context
context ,L
ist <?
e
xtendsMap
<S
tring
,?
>>
data,i
nt
resource
,
String
[] f
rom ,i
nt
[]
to){
super
(c
ontext ,
data,
resource ,f
rom,to
);
}
@Override
publicV
iew getView(i
ntposition ,V
iewconvertView ,ViewGroup
parent
){
returns
uper .g
etView(p
osition ,
convertView ,
parent
);
}
@Override
publici
nt
getCount ()
{
returns
uper .g
etCount();
}
}
TheaboveoverridedfunctionsofsimpleadapterarealreadydescribedinCustom
SimpleAdapterarticle.
AdapterExampleInAndroidStudio:
BelowistheAndroidStudioexamplewhichshowtheuseoftheAdapterinAndroid.Inthis
examplewedisplayalistoffruitsnameswithimagesbyusingSimpleAdapterandwhenever
userclickonalistitemthefruit’snamedisplayedinaToast.
BelowyoucandownloadcompleteAndroidStudiocode,seefinaloutputandreadstepbystep
explanation:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
78
Step1:C
reateanewprojectandnameitSimpleAdapterExample.
Step2:Openres->layout->xml(or)main.xmlandaddfollowingcode:
InthisstepweopenanxmlfileandaddthecodefordisplayingaListViewbyusingitsdifferent
attributes.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns
:t
ools="http://schemas.android.com/tools"
android
:l
ayout_width ="
match_parent"
android
:l
ayout_height ="match_parent"
tools
:c
ontext ="
.MainActivity">
<ListView
android
:i
d="
@+id/simpleListView"
android
:l
ayout_width ="
match_parent"
android
:l
ayout_height ="wrap_content"
android
:d
ivider ="
#000"
android
:d
ividerHeight ="2dp"
android
:l
istSelector ="
#600"/>
</RelativeLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
79
Step3:S avefruitimagesindrawablefolderwithnameapple,banana,litchi,mangoand
pineapple.
Step4:O
pensrc->package->MainActivity.java
InthisstepweaddthecodeforinitiateListViewandsetthedatainthelist.Inthisfirstlywe
createtwoarraysfirstforfruitnamesandsecondforfruitsimagesandthensetthedatainthe
ListViewusingSimpleAdapter.
packageexample .abhiandriod .simpleadapterexample;
import
android .s
upport .v7.app.AppCompatActivity;
import
android .o
s.B
undle;
import
android .v
iew .Menu;
import
android .v
iew .MenuItem;
import
android .v
iew .View;
import
android .w
idget .A
dapterView;
import
android .w
idget .L
istView;
import
android .w
idget .S
impleAdapter;
import
android .w
idget .T
oast;
import
java .u
til .ArrayList;
import
java .u
til .HashMap;
publicc
lass MainActivity extends AppCompatActivity {
//initialize
view's
ListView
simpleListView;
String
[]
fruitsNames= {"Apple" ,"Banana" ,"Litchi" ,"Mango","PineApple"};
//fruitnames
array
int
[]fruitsImages= {R.
drawable .a
pple ,R.
drawable .b
anana,
R.d
rawable.litchi
,
R
.d
rawable .m
ango , R.
d
rawable .pineapple };
//fruits images
@Override
protected
void
onCreate (Bundle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.l
ayout .activity_main );
s
impleListView =(ListView )f
indViewById (R.
id.s
impleListView );
ArrayList
<HashMap <String ,S
tring >>
arrayList =n
ewArrayList<>();
for
(
inti=
0;
i<
f
ruitsNames .length ;i+
+)
{
HashMap <String ,S
tring >hashMap =n
ew H
ashMap <>();//create a
hashmaptostore
the
datainkey value pair
h
ashMap .put("
name" ,f
ruitsNames [i
]);
h
ashMap .put("
image" ,fruitsImages [i
]+"");
a
rrayList .a
dd (hashMap );//add the hashmap intoarrayList
}
String
[]f
rom ={"name" ,"image" };//string array
int
[]to
={R.i
d.t
extView ,R
.i
d .i
mageView };//int arrayof
views id's
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
80
SimpleAdapter
simpleAdapter =n
ew
SimpleAdapter (this,a
rrayList,R
.l
ayout .list_view_items,f
rom
,to
);//Create
objectand setthe
parameters for simpleAdapter
s
impleListView .setAdapter (s
impleAdapter );
//setstheadapterfor
listView
//perform
listViewitem click event
s
impleListView .setOnItemClickListener (n
ew
A
dapterView .OnItemClickListener ()
{
@Override
public v
oid
onItemClick (A
dapterView<?>
adapterView ,V
iew
view,i
nt
i,l
ong
l)
{
Toast
.makeText (g
etApplicationContext (),fruitsNames
[i]
,
Toast
.LENGTH_LONG).
show();
//show the
selected image intoastaccording to position
}
});
}
}
Step5:Createnewlayout->rec->layout->list_view_items.xmlandaddfollowingcode:
InthisstepwecreateaxmlfilefordisplayingListViewitems.Inthisxmlweaddthecodefor
displayingaImageViewandaTextView.
<?
xml
version ="1.0"encoding ="utf-8"
?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android
:l
ayout_width ="
match_parent"
android
:l
ayout_height ="wrap_content"
android
:b
ackground ="#fff">
<ImageView
android
:i
d="
@+id/imageView"
android
:l
ayout_width ="
50dp"
android
:l
ayout_height ="50dp"
android
:p
adding ="
5dp"
android
:l
ayout_alignParentRight ="
true"
android
:l
ayout_marginRight ="
10dp"
android
:s
rc="@drawable/ic_launcher" /
>
<TextView
android
:i
d="
@+id/textView"
android
:l
ayout_width ="
wrap_content"
android
:l
ayout_height ="wrap_content"
android
:p
adding ="
@dimen/activity_horizontal_margin"
android
:t
ext ="
Demo"
android
:t
extColor ="
#000" /
>
</RelativeLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
81
Output:
NowruntheAppandyouwilldifferentfruitnameslistedinListView.HereweusedSimple
AdaptertofilldatainListView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
82
ListView
ListViewisalistofscrollableitemscanbedisplayedinAndroidusingListView.Ithelpsyouto
displayingthedataintheformofascrollablelist.Userscanthenselectanylistitembyclicking
onit.ListViewisdefaultscrollablesowedonotneedtousescrollVieworanythingelsewith
ListView.
ListViewiswidelyusedinandroidapplications.AverycommonexampleofListViewisyour
phonecontactbook,whereyouhavealistofyourcontactsdisplayedinaListViewandifyou
clickonitthenuserinformationisdisplayed.
Adapter:TofillthedatainaListViewwesimplyuseadapters.Listitemsareautomatically
insertedtoalistusinganAdapterthatpullsthecontentfromasourcesuchasanarraylist,
arrayordatabase.
ListViewinAndroidStudio:L
istviewispresentinsideContainers.Fromthereyoucandrag
anddroponvirtualmobilescreentocreateit.AlternativelyyoucanalsoXMLcodetocreateit.
HereisAndroidListViewXMLCode:
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools="
http://schemas.android.com/tools"
a
ndroid
:i
d
="
@+id/simpleListView"
a
ndroid
:l
ayout_width="
match_parent"
a
ndroid
:l
ayout_height="wrap_content"
t
ools
:c
ontext="
abhiandroid.com.listexample.MainActivity">
</ListView>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
83
ListviewlookinDesign:
AttributesofListView:
LetsseesomedifferentattributesofListViewwhichwillbeusedwhiledesigningacustomlist:
1.id:idisusedtouniquelyidentifyaListView.
Belowistheidattribute’sexamplecodewithexplanationincluded.
<!--
Id
ofa
list
viewuniquely
identify
it-->
<ListView
android
:i
d="
@+id/simpleListView"
android
:l
ayout_width="
fill_parent"
android
:l
ayout_height="wrap_content"
/>
2.divider:Thisisadrawableorcolortodrawbetweendifferentlistitems.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
84
Belowisthedividerexamplecodewithexplanationincluded,wherewedrawredcolordivider
betweendifferentviews.
<!--Divider codein
ListView-->
<ListView
android
:i
d="
@+id/simpleListView"
android
:l
ayout_width ="
fill_parent"
android
:l
ayout_height ="wrap_content"
android
:d
ivider ="
#f00"
android
:d
ividerHeight ="1dp"
/>
3.dividerHeight:T
hisspecifytheheightofthedividerbetweenlistitems.Thiscouldbein
dp(densitypixel),sp(scaleindependentpixel)orpx(pixel).
Inaboveexampleofdividerwealsosetthedividerheight1dpbetweenthelistitems.The
heightshouldbeindp,sporpx.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
85
4.listSelector:l istSelectorpropertyisusedtosettheselectorofthelistView.Itisgenerally
orangeorSkybluecolormostlybutyoucanalsodefineyourcustomcolororanimageasalist
selectorasperyourdesign.
BelowislistSelectorexamplecodewithexplanationincludes,wherelistselectorcolorisgreen,
whenyouselectanylistitemthenthatitem’sbackgroundcolorisgreen.
<!--
List Selector
Codein
ListView
-->
<ListView
android
:i
d="@+id/simpleListView"
android
:l
ayout_width ="
fill_parent"
android
:l
ayout_height ="wrap_content"
android
:d
ivider ="
#f00"
android
:d
ividerHeight ="1dp"
android
:l
istSelector ="
#0f0"/>
<
!--
list
selectori
n
green
color
-->
AdaptersUseinListView:
AnadapterisabridgebetweenUIcomponentanddatasourcethathelpsustofilldatainUI
component.Itholdsthedataandsendthedatatoadapterviewthenviewcantakesthedata
fromtheadapterviewandshowsthedataondifferentviewslikeaslistview,gridview,spinner
etc.
ListViewisasubclassofAdapterViewanditcanbepopulatedbybinding toanAdapter,which
retrievesthedatafromanexternalsourceandcreatesaViewthatrepresentseachdataentry.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
86
Inandroidcommonlyusedadaptersare:
ArrayAdapter
BaseAdapter
Nowweexplainthesetwoadapterindetail:
1.ArrayAdapter:
Wheneveryouhavealistofsingleitemswhichisbackedbyanarray,youcanuseArrayAdapter.
Forinstance,listofphonecontacts,countriesornames.
ImportantNote:B
ydefault,ArrayAdapterexpectsaLayoutwithasingleTextView,Ifyou
wanttousemorecomplexviewsmeansmorecustomizationinlistitems,pleaseavoid
ArrayAdapterandusecustomadapters.
BelowisArrayAdaptercode:
ArrayAdapter
adapter=
n
ew
ArrayAdapter
<String
>(
this
,R.
layout
.L
istView
,R
.i
d
.t
extView
,S
tringArray
);
ExampleoflistviewusingArrayAdapter:
Inthisexample,wedisplayalistofcountriesbyusingsimplearrayadapter.Belowisthefinal
outputwewillcreate:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
87
Step1:CreateanewprojectListexampleandactivityMainActivity.Herewewillcreatea
ListViewinLinearLayout.Belowisthecodeofactivity_main.xmlorcontent_main.xml:
<?
xml
version
="
1.0"
encoding
="
utf-8"
?>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
88
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android
:l
ayout_width="match_parent"
android
:l
ayout_height ="
match_parent"
android
:o
rientation="
vertical">
<ListView
android
:i
d="
@+id/simpleListView"
android
:l
ayout_width="fill_parent"
android
:l
ayout_height ="
wrap_content"
android
:d
ivider="
@color/material_blue_grey_800"
android
:d
ividerHeight ="
1dp"
/
>
</LinearLayout>
Step2:C
reateanewactivitynameListviewandbelowisthecodeofactivity_listview.xml
<?
xml
version="
1.0"
encoding="
utf-8" ?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android
:l
ayout_width ="match_parent"
android
:l
ayout_height ="
match_parent"
android
:o
rientation ="
vertical">
<TextView
android
:i
d="
@+id/textView"
android
:l
ayout_width ="fill_parent"
android
:l
ayout_height ="
wrap_content"
android
:l
ayout_gravity ="
center"
android
:p
adding="@dimen/activity_horizontal_margin"
android
:t
extColor ="
@color/black" /
>
</LinearLayout>
Step3:N
owinthisfinalstepwewilluseArrayAdaptertodisplaythecountrynamesinUI.
BelowisthecodeofMainActivity.java
package abhiandroid .com
.listexample;
import
android .os
.B
undle;
import
android .app
.Activity;
import
android .view.Menu;
import
android .widget .A
rrayAdapter ;i
mport
android .w
idget
.ListView;
public c
lassMainActivity extends Activity
{
//Array ofstrings...
ListView
simpleList;
String
countryList []=
{"
India" ,"
China" ,"australia" ,"Portugle" ,"
America",
"NewZealand" };
@Override p rotected voidonCreate(B
undle savedInstanceState ) {
super
.o
nCreate (savedInstanceState );
setContentView(R
.l
ayout .a
ctivity_main
);
s
impleList= (L
istView )findViewById (R
.i
d.simpleListView);
ArrayAdapter
<S
tring >arrayAdapter= new A
rrayAdapter <S
tring>(this,
R
.layout.activity_listview ,
R.i
d.t
extView,countryList );
s
impleList .s
etAdapter (a
rrayAdapter );
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
89
OutputScreen:
NowruntheAppinEmulator.Youwillseethebelowoutputscreenwherelistofcountrynames
willbeprinted:
2.BaseAdapter:
BaseAdapterisacommonbaseclassofageneralimplementationofanAdapterthatcanbe
usedinListView.Wheneveryouneedacustomizedlistyoucreateyourownadapterandextend
baseadapterinthat.BaseAdaptercanbeextendedtocreateacustomAdapterfordisplayinga
customlistitem. ArrayAdapterisalsoanimplementationofBaseAdapter.
E
xampleoflistviewusingCustomadapter(Baseadapter):
Inthisexamplewedisplayalistofcountrieswithflags.Forthis,wehavetousecustomadapter
asshowninexample:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
90
Step1:CreateanewprojectListebasexampleandactivityMainActivity.Herewewillcreatea
ListViewinLinearLayout.Belowisthecodeofactivity_main.xmlorcontent_main.xml:
<?
xml
version="
1.0"
encoding="
utf-8" ?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android
:l
ayout_width ="match_parent"
android
:l
ayout_height ="
match_parent"
android
:o
rientation ="
vertical">
<ListView
android
:i
d="
@+id/simpleListView"
android
:l
ayout_width ="fill_parent"
android
:l
ayout_height ="
wrap_content"
android
:d
ivider="@color/material_blue_grey_800"
android
:d
ividerHeight ="
1dp"
android
:f
ooterDividersEnabled ="false" /
>
</LinearLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
91
Step2:C
reateanewactivitynameListviewandbelowisthecodeofactivity_listview.xml
<?
xml
version ="
1.0"
encoding ="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android
:l
ayout_width ="match_parent"
android
:l
ayout_height ="
match_parent"
android
:o
rientation ="
horizontal">
<ImageView
android
:i
d="
@+id/icon"
android
:l
ayout_width ="50dp"
android
:l
ayout_height ="
50dp"
android
:s
rc="@drawable/ic_launcher" />
<TextView
android
:i
d="
@+id/textView"
android
:l
ayout_width ="fill_parent"
android
:l
ayout_height ="
wrap_content"
android
:l
ayout_gravity ="center"
android
:p
adding ="@dimen/activity_horizontal_margin"
android
:t
extColor ="
@color/black" /
>
</LinearLayout>
Step3:I nthirdstepwewillusecustomadaptertodisplaythecountrynamesinUIbycoding
MainActivity.java.BelowisthecodeofMainActivity.java
ImportantNote:Makesureflagimagesarestoredindrawablefolderpresentinsideresfolder
withcorrectnaming.
packagecom.a
bhiandroid .listbaseexample;
import
android .a
pp.Activity;
import
android .o
s.B
undle;
import
android .w
idget .ListView;
publicc
lass MainActivity extendsA
ctivity
{
ListView
simpleList;
String
countryList []=
{"India","China","
australia" ,"
Portugle","
America"
,"
NewZealand"
};
int
flags[]=
{R
.
drawable .i
ndia,R.
drawable.c
hina
,
R.d
rawable
.a
ustralia,
R
.d
rawable .portugle ,
R.d
rawable .america,
R.d
rawable
.new_zealand};
@Override
protected void
onCreate (Bundle
savedInstanceState )
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
92
super
.o
nCreate (s
avedInstanceState);
setContentView (R
.l
ayout
.a
ctivity_main);
simpleList=(
ListView)
findViewById(R
.i
d
.s
impleListView
);
CustomAdaptercustomAdapter=n
ew
C
ustomAdapter (g
etApplicationContext
(),
countryList
,
flags
);
simpleList
.s
etAdapter (c
ustomAdapter);
}
}
Step4:NowcreateanotherclassCustomAdapterwhichwillextendBaseAdapter.Belowisthe
codeofCustomAdapter.java
packagecom.abhiandroid .l
istbaseexample;
import
android .content .Context;
import
android .media .I
mage;
import
android .view.LayoutInflater;
import
android .view.View;
import
android .view.ViewGroup;
import
android .widget .BaseAdapter;
import
android .widget .ImageView;
import
android .widget .TextView;
import
java .util .z
ip.Inflater;
publicc
lass CustomAdapter extends B
aseAdapter
{
Contextcontext;
String
countryList [];
int
flags [];
LayoutInflater inflter;
publicC
ustomAdapter (C
ontext
applicationContext ,S
tring
[]
countryList
,i
nt
[]
flags
)
{
this
.context =context;
this
.countryList=
countryList;
this
.flags= flags;
inflter= (L
ayoutInflater .from (applicationContext));
}
@Override
publici
nt
getCount ()
{
return
countryList .l
ength;
}
@Override
publicO
bject
getItem (int
i){
returnn
ull;
}
@Override
publicl
ong getItemId (int
i){
return0
;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
93
}
@Override
publicV
iew
getView (i
nti,
V
iew
view,V
iewGroup
viewGroup) {
view=
inflter .i
nflate (R
.l
ayout.a
ctivity_listview ,null
);
TextView
country= (T
extView ) v
iew
.f
indViewById (R
.i
d.t
extView
);
ImageView icon=
(I
mageView )view.f
indViewById
(R.
id
.i
con
);
country.setText(c
ountryList [i]
);
icon
.s
etImageResource (f
lags[i]
);
return
view;
}
Output:
NowruntheAppinEmulatoranditwillshowyounameofcountriesalongwithflags.Belowis
theoutputscreen:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
94
GridView
InandroidGridViewisaviewgroupthatdisplayitemsintwodimensionalscrollinggrid(rows
andcolumns),thegriditemsarenotnecessarilypredeterminedbuttheyareautomatically
insertedtothelayoutusingaListAdapter.Userscanthenselectanygriditembyclickingonit.
GridViewisdefaultscrollablesowedon’tneedtouseScrollVieworanythingelsewith
GridView.
GridViewiswidelyusedinandroidapplications.AnexampleofGridViewisyourdefault
Gallery,whereyouhavenumberofimagesdisplayedusinggrid.
AdapterIsUsedToFillDataInGridview:T
ofillthedatainaGridViewwesimplyuse
adapterandgriditemsareautomaticallyinsertedtoaGridViewusinganAdapterwhichpulls
thecontentfromasourcesuchasanarraylist,arrayordatabase.
GridViewinAndroidStudio:GridviewispresentinsideContainers.Fromthereyoucan
draganddroponvirtualmobilescreentocreateit.AlternativelyyoucanalsoXMLcodeto
createit.
BasicGridViewcodeinXML:
<GridView
android
:i
d="
@+id/simpleGridView"
android
:l
ayout_width ="
fill_parent"
android
:l
ayout_height ="wrap_content"
android
:n
umColumns="
3"/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
95
ImportantNote:n
umColumnspropertyhastobespecifiedotherwiseGridViewbehaveslikea
ListViewwithjustsingleChoice.IntheaboveimagenumColumnspropertyspecifiedthatthere
is3columnstoshow,ifwesetittoauto_fitthenitautomaticallydisplayasmanycolumnas
possibletofilltheavailablespaceofthescreen.Evenifthephoneisinportraitmodeor
landscapemodeitautomaticallyfillthewholespace.
AttributesofGridView:
LetsseedifferentattributesofGridViewwhichwillbeusedwhiledesigningacustomgridview:
1.id:idisusedtouniquelyidentifyaGridView.
Belowistheidattribute’sexamplecodewithexplanationincludedinwhichwedon’tspecifythe
numberofcolumnsinarowthat’swhytheGridViewbehaveslikeaListView.
BelowistheidattributeexamplecodeforGridview:
<GridView
android
:i
d="
@+id/simpleGridView"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
96
android
:l
ayout_width
="
fill_parent"
android
:l
ayout_height
="wrap_content"
/>
2.numColumns:n
umColumndefinehowmanycolumnstoshow.It maybeaintegervalue,
suchas“5”orauto_fit.
auto_fit isusedtodisplayasmanycolumnsaspossibletofilltheavailablespaceonthescreen.
ImportantNote:Ifwedon’tspecifynumColumnpropertyinGridViewitbehaveslikea
ListViewwithsingleChoice.
BelowisthenumColumnsexamplecodewherewedefine4columnstoshowinthescreen.
<!--
numColumnsexample code
-->
<GridView
android
:i
d="
@+id/simpleGridView"
android
:l
ayout_width ="
fill_parent"
android
:l
ayout_height ="wrap_content"
android
:n
umColumns="
4"/><
!--
numColumns
set
to4
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
97
3.horizontalSpacing:horizontalSpacingpropertyisusedtodefinethedefaulthorizontal
spacingbetweencolumns.Thiscouldbeinpixel(px),densitypixel(dp)orscaleindependent
pixel(sp).
BelowisthehorizontalSpacingexamplecodewithexplanationincludedwherehorizontal
spacingbetweengriditemsis50dp.
<!--Horizontalspaceexample
code
ingrid
view-->>
<GridView
android
:i
d="
@+id/simpleGridView"
android
:l
ayout_width ="
fill_parent"
android
:l
ayout_height ="
wrap_content"
android
:n
umColumns="
3"
android
:h
orizontalSpacing ="
50dp"
/><!--50dp
horizontal
space
between
grid
items
-->
4.verticalSpacing:verticalSpacingpropertyusedtodefinethedefaultverticalspacing
betweenrows.Thisshouldbeinpx,dporsp.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
98
BelowistheverticalSpacingexamplecodewithexplanationincluded,whereverticalspacing
betweengriditemsis50dp.
<!--
Verticalspacebetweengriditems
code-->
<GridView
android
:i
d="
@+id/simpleGridView"
android
:l
ayout_width ="
fill_parent"
android
:l
ayout_height ="
wrap_content"
android
:n
umColumns="
3"
android
:v
erticalSpacing ="
50dp"
/><!--50dp
vertical
space
set
between
grid
items
-->
5.columnWidth:columnWidthpropertyspecifiesthefixedwidthofeachcolumn.Thiscould
beinpx,dporsp.
BelowisthecolumnWidthexamplecode.Herecolumnwidthis80dpandselecteditem’s
backgroundcolorisgreenwhichshowstheactualwidthofagriditem.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
99
ImportantNote:I nthebelowcodewealsousedlistSelectorpropertywhichdefinecolorfor
selecteditem.AlsotoseetheoutputofcolumnWidthusinglistSelectorweneedtouseAdapter
whichisournexttopic.Thebelowcodeisnotsufficienttoshowyoutheoutput.
<!--columnWidthin
Grid viewcode-->
<GridView
android
:i
d="
@+id/simpleGridView"
android
:l
ayout_width ="
fill_parent"
android
:l
ayout_height ="wrap_content"
android
:n
umColumns="
3"
android
:c
olumnWidth="
80dp"
android
:l
istSelector ="
#0f0" /><!--
define
green
colorf
or
selected
item
-->
GridViewExampleUsingDifferentAdaptersInAndroidStudio:
AnadapterisabridgebetweenUIcomponentanddatasourcethathelpsustofilldatainUI
component.Itholdsthedataandsendsthedatatoadapterview,thenviewcantakesthedata
fromtheadapterviewandshowsthedataondifferentviewslikeaslistview,gridview,spinner
etc.
GridViewandListViewbotharesubclassesofAdapterViewanditcanbepopulatedbybinding
toanAdapter,whichretrievesthedatafromanexternalsourceandcreatesaViewthat
representseachdataentry.InandroidcommonlyusedadapterswhichfilldatainGridVieware:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
100
1.ArrayAdapter
2.BaseAdapter
3.CustomArrayAdapter
Nowweexplaintheseadaptersindetail:
1.AvoidArrayAdapterToFillDataInGridView:
Wheneveryouhavealistofsingleitemswhichisbackedbyanarray,youcanuseArrayAdapter.
Forinstance,listofphonecontacts,countriesornames.
Bydefault,ArrayAdapterexpectsaLayoutwithasingleTextView,Ifyouwanttousemore
complexviewsmeansmorecustomizationingriditems,pleaseavoidArrayAdapteranduse
customadapters.
ArrayAdapter
adapter=
n
ew
ArrayAdapter
<String
>(
this
,R.
layout
.L
istView
,R
.i
d
.t
extView
,S
tringArray
);
2.GridViewUsingBaseAdapterInAndroid:
BaseAdapterisacommonbaseclassofageneralimplementationofanAdapterthatcanbe
usedinGridView.Wheneveryouneedacustomizedgridviewyoucreateyourownadapterand
extendbaseadapterinthat.BaseAdaptercanbeextendedtocreateacustomAdapterfor
displayingcustomgriditems.ArrayAdapterisalsoanimplementationofBaseAdapter.Youcan
readBaseAdaptertutorialhere.
ExampleofGridViewusingBaseAdapterinAndroidStudio:B
elowistheexampleof
GridViewinAndroid,inwhichweshowtheAndroidlogo’sintheformofGrids.Inthisexample
firstlywecreateaninttypearrayforlogoimagesandthencalltheAdaptertosetthedatainthe
GridView.InthiswecreateaCustomAdapterbyextendingBaseAdapterinit.AtLastwe
implementsetOnItemClickListenereventonGridViewandonclickofanyitemwesendthat
itemtoanotherActivityandshowthelogoimageinfullsize.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
101
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanationoftheexample.
Step1:CreateanewAndroidprojectinAndroidStudioandfillalltherequireddetails.Inour
casewehavenamedGridViewExampleandpackagecom.example.gourav.GridViewExample
Step2:O
penactivity_main.xmlandpastethebelowcode.InthiswehavecreatedaGridview
insideLinearLayoutandalsosetnumberofcolumnsto3.
<?
xml
version="1.0" encoding="
utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid:l
ayout_width ="match_parent"
a
ndroid:l
ayout_height ="
match_parent"
a
ndroid:o
rientation ="
vertical">
<!--
GridView
with 3
valuefor
numColumnsattribute
-->
<
GridView
a
ndroid :i
d="
@+id/simpleGridView"
a
ndroid :l
ayout_width ="
fill_parent"
a
ndroid :l
ayout_height ="wrap_content"
a
ndroid :f
ooterDividersEnabled ="
false"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
102
a
ndroid
:padding
="
1dp"
a
ndroid
:numColumns
="
3"/
>
</LinearLayout>
Step3:CreateanewXMLfileandpastethebelowcode.Wehavenamedactivity_gridview.xml.
InthisstepwecreateanewXMLfileandaddaImageViewinit.Thisfileisusedin
CustomAdaptertosetthelogoimages
<?
xml
version
="
1.0" encoding="
utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
a
ndroid
:l
ayout_width ="match_parent"
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:p
adding ="
1dp"
a
ndroid
:o
rientation ="
vertical">
<
ImageView
a
ndroid:id
="
@+id/icon"
a
ndroid:layout_width ="
match_parent"
a
ndroid:layout_height ="120dp"
a
ndroid:scaleType ="
fitXY"
a
ndroid:layout_gravity ="
center_horizontal"
a
ndroid:src
="
@drawable/logo1" />
</LinearLayout>
Step4:Nowopendrawablefolderandsavesmallsizepngimagesofdifferentlogo’sandname
themlikelogo1,logo2andetc.
Step5:N
owopenMainActivity.javaandpastethebelowcode.Ifyourpackagenameis
different,don’tcopyit.
InthisstepfirstlywegetthereferenceofGridViewandthencreateainttypearrayforAndroid
logo’s.AfterthatwecalltheCustomAdapterandpassthearrayinit.AtLastweimplement
setOnItemClickListenereventonGridViewandonclickofanyitemwesendthatitemto
anotherActivitytoshowthelogoimageinFullSize.Ihaveaddedcommentsincodetohelpyou
tounderstandthecodeeasilysomakeyoureadthecomments.
package
com
.e
xample .gourav .GridViewExample;
import
android .c
ontent .I
ntent;
import
android .o
s.B
undle;
import
android .s
upport .v
7.app
.A
ppCompatActivity;
import
android .v
iew .V
iew;
import
android .w
idget .AdapterView;
import
android .w
idget .GridView;
public
c
lassMainActivity extends A
ppCompatActivity
{
GridView
simpleGrid;
int
logos[]=
{R
.d
rawable .l
ogo1 ,
R.d
rawable.l
ogo2 ,R.
drawable
.l
ogo3 ,
R.d
rawable.l
ogo4,
R
.d
rawable .l
ogo5 ,R.drawable .l
ogo6
,
R.d
rawable .l
ogo7
,R.
drawable .l
ogo8
,
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
103
R
.drawable.l
ogo9,
R
.d
rawable .l
ogo10 ,R.d
rawable .l
ogo11 ,
R.d
rawable .l
ogo12,R.
drawable.l
ogo13};
@Override
protected
void
onCreate (B
undle
savedInstanceState ){
super
.onCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .activity_main );
s
impleGrid= (
GridView )findViewById (R.
id
.s
impleGridView );
/
/init GridView
//
Create an
object of CustomAdapter andset Adapter toGirdView
CustomAdapter
customAdapter= n
ewC
ustomAdapter (getApplicationContext (),
logos
);
s
impleGrid .s
etAdapter (customAdapter );
//
implement setOnItemClickListener event onGridView
s
impleGrid .s
etOnItemClickListener (n
ew A
dapterView .O
nItemClickListener ()
{
@Override
public v
oidonItemClick (AdapterView <?>
parent ,View
view,i
nt
position ,l
ong
id
)
{
//
setan Intent to Another Activity
Intent
intent= newI
ntent (MainActivity .this,SecondActivity .c
lass);
i
ntent .p
utExtra ("image" ,logos [position ]);//put
image datainIntent
s
tartActivity (i
ntent );
//
start Intent
}
});
}
}
Step6:C
reateanewclassCustomAdapterandpastethebelowcode.
InthisstepwecreateaCustomAdapterclassbyextendingBaseAdapterinit.Inthisstepweset
thelogoimage’sinthegriditems.Ihaveaddedcommentsincodetohelpyoutounderstandthe
codeeasilysomakeyoureadthecomments.
packagecom
.e
xample .gourav .GridViewExample;
import
android .content .C
ontext;
import
android .view .L
ayoutInflater;
import
android .view .V
iew;
import
android .view .V
iewGroup;
import
android .widget .BaseAdapter;
import
android .widget .ImageView;
publicc
lassCustomAdapter extends B
aseAdapter
{
Context
context;
int
logos[];
LayoutInflater
inflter;
public
C
ustomAdapter (C
ontext
applicationContext ,i
nt
[]
logos
)
{
this
.c
ontext=
applicationContext;
this
.l
ogos= logos;
i
nflter= (
LayoutInflater .from
(a
pplicationContext ));
}
@Override
public
i
ntgetCount ()
{
return
logos .length;
}
@Override
public
O
bject
getItem (int
i){
return
n
ull;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
104
}
@Override
public
l
ong getItemId (i
nt
i)
{
return
0
;
}
@Override
public
V
iew getView(int
i,V
iew view
,ViewGroup
viewGroup )
{
v
iew= inflter .i
nflate (R.
layout.a
ctivity_gridview ,n
ull);/
/inflate
the
layout
ImageView
icon=
(I
mageView )view.f
indViewById(R
.i
d
.icon);/
/
get
the
reference
of
ImageView
i
con .s
etImageResource (l
ogos [i]
);
//
set
logoimages
return
view;
}
}
Step7:N
owCreateanewXMLfilenamedactivity_secondandpastethebelowcodeinit.
InthisstepwecreateanXMLfileforourSecondActivitytodisplaythelogoimageinfullsize.
<?
xml
version
="
1.0" encoding ="
utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools="
http://schemas.android.com/tools"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop ="
@dimen/activity_vertical_margin"
a
ndroid
:b
ackground ="
#fff"
t
ools
:c
ontext="com.example.gourav.GridViewExample.SecondActivity">
<
ImageView
a
ndroid:i
d="
@+id/selectedImage"
a
ndroid:l
ayout_width ="
match_parent"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:l
ayout_centerInParent ="
true"
a
ndroid:s
caleType ="fitXY"/
>
</RelativeLayout>
Step8:N
owCreateanewActivitywithnameSecondActivity.classandaddbelowcodeinit.
InthisstepwecreateanewActivityinwhichfirstlyweinitiatetheImageViewandthengetthe
ImagefromourPreviousActivitybyusingIntentobjectandsetthesameintheImageView.
package
com
.e
xample
.g
ourav
.GridViewExample;
import
android.c
ontent
.I
ntent;
import
android.o
s
.B
undle;
import
android.s
upport
.v
7
.app
.A
ppCompatActivity;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
105
import
android .w
idget
.I
mageView;
publicc
lassS
econdActivity e
xtendsA
ppCompatActivity
{
ImageView
selectedImage;
@Override
protected
void
onCreate (B
undle
savedInstanceState ){
super
.onCreate(s
avedInstanceState );
s
etContentView (R
.l
ayout
.a
ctivity_second );
s
electedImage= (I
mageView)
findViewById (R
.i
d
.s
electedImage );/
/ init
a
ImageView
Intent
intent=getIntent();/
/get
Intent which we
set
fromPrevious Activity
s
electedImage.setImageResource (i
ntent.g
etIntExtra ("
image"
,0
));/
/get
imagefrom
Intentandsetit
in
ImageView
}
}
Output:N
owruntheAppandyouwillseedifferentAndroidimagesinGridView.Clickonthe
anyimageandfullsizeofitwillopenup.
3.GridViewExampleUsingCustomArrayAdapterInAndroidStudio:
ArrayAdapterisalsoanimplementationofBaseAdaptersoifwewantmorecustomizationthen
wecreateacustomadapterandextendArrayAdapterinthat.HerewearecreatingGridView
usingcustomarrayadapter.
ExampleofGridViewusingCustomAdapter:ExampleofGridViewusingcustom
arrayadaptertoshowbirdsintheformofgrids.Belowisthecodeandfinaloutput:
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanationofthetopic.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
106
Step1:CreateanewprojectandnameitGridViewExample.
Step2:N
owopenapp->res->layout->activity_main.xml(or)main.xmlandaddfollowing
code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools="http://schemas.android.com/tools"
a
ndroid
:i
d="
@+id/activity_main"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop ="
@dimen/activity_vertical_margin"
t
ools
:c
ontext ="
abhiandroid.com.gridviewexample.MainActivity">
<
GridView
a
ndroid:id
="@+id/simpleGridView"
a
ndroid:layout_width ="
match_parent"
a
ndroid:layout_height ="wrap_content"
a
ndroid:numColumns ="3"
/>
</RelativeLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
107
Step3:CreateanewlayoutActivityinapp->res->layout->newactivityandnameit
grid_view_items.xmlandaddfollowingcode:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools="http://schemas.android.com/tools"
a
ndroid
:i
d="
@+id/grid_view_items"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop ="
@dimen/activity_vertical_margin"
t
ools
:c
ontext ="
abhiandroid.com.gridviewexample.GridViewItems">
<
ImageView
a
ndroid:id
="@+id/imageView"
a
ndroid:layout_width ="
150dp"
a
ndroid:layout_height ="150dp"
a
ndroid:padding="5dp"
a
ndroid:scaleType ="fitXY"
a
ndroid:src
="@drawable/ic_launcher"
a
ndroid:layout_alignParentTop ="
true"
a
ndroid:layout_centerHorizontal ="true" /
>
<
TextView
a
ndroid:id
="@+id/textView"
a
ndroid:layout_width ="
wrap_content"
a
ndroid:layout_height ="wrap_content"
a
ndroid:padding="@dimen/activity_horizontal_margin"
a
ndroid:text="
Demo"
a
ndroid:textColor ="#000"
a
ndroid:layout_below ="
@+id/imageView"
a
ndroid:layout_centerHorizontal ="true"
a
ndroid:layout_marginTop ="13dp" /
>
</RelativeLayout>
Step4:Nowopenapp->java->package->MainActivity.java
import
android.s
upport.v
7.app
.A
ppCompatActivity;
import
android.o
s
.B
undle;
import
android.s
upport.v
7.app
.A
ppCompatActivity;
import
android.o
s
.B
undle;
import
android.v
iew.M
enu;
import
android.v
iew.M
enuItem;
import
android.w
idget.G
ridView;
import
java
.u
til.A
rrayList;
public
c
lass
MainActivity extendsA
ppCompatActivity
{
GridView
simpleList;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
108
rrayList
A birdList=n
ew A
rrayList <>();
@Override
protected
v
oid
onCreate (Bundle
savedInstanceState )
{
super
.o
nCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .a
ctivity_main );
s
impleList=(
GridView )findViewById (R
.i
d
.s
impleGridView
);
b
irdList.a
dd
(n
ewItem ("
Bird1"
,R.
drawable.b
1
));
b
irdList.a
dd
(n
ewItem ("
Bird2"
,R.
drawable.b
2
));
b
irdList.a
dd
(n
ewItem ("
Bird3"
,R.
drawable.b
3
));
b
irdList.a
dd
(n
ewItem ("
Bird4"
,R.
drawable.b
4
));
b
irdList.a
dd
(n
ewItem ("
Bird5"
,R.
drawable.b
5
));
b
irdList.a
dd
(n
ewItem ("
Bird6"
,R.
drawable.b
6
));
yAdapter
M
myAdapter
=n
ewM
yAdapter
(t
his
,R.
layout
.g
rid_view_items
,b
irdList
);
s
impleList
.s
etAdapter
(m
yAdapter);
}
}
Step5:CreateanewClasssrc->package->MyAdapter.javaandaddthefollowingcode:
import
android .c
ontent .C
ontext;
import
android .v
iew .L
ayoutInflater;
import
android .v
iew .V
iew;
import
android .v
iew .V
iewGroup;
import
android .w
idget .ArrayAdapter;
import
android .w
idget .ImageView;
import
android .w
idget .TextView;
import
java.util .A
rrayList;
publicc
lass M
yAdapter e
xtends A
rrayAdapter {
ArrayList
birdList= new A
rrayList <>();
public
MyAdapter (Context
context ,i
nttextViewResourceId ,ArrayList
objects)
{
super
(context ,textViewResourceId ,objects);
b
irdList= objects;
}
@Override
public
int
getCount ()
{
return
s
uper .getCount ();
}
@Override
public
ViewgetView (intposition ,V
iew
convertView ,ViewGroup
parent){
View
v=convertView;
LayoutInflater
inflater= (
LayoutInflater )
getContext ().getSystemService (Context .L
AYOUT_INFLATER_SERVICE );
v
=
inflater .inflate (R.l
ayout .g
rid_view_items ,null );
TextView
textView= (T
extView )v.
findViewById (R
.i
d.textView);
ImageView
imageView= (ImageView )v.
findViewById (R.
id
.imageView
);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
109
t
extView.s
etText(b
irdList
.g
et(p
osition
).getbirdName
());
i
mageView.setImageResource(b
irdList
.g
et(p
osition
).
getbirdImage
());
return
v;
}
}
Step6:CreateanewClasssrc->package->Item.javaandaddthebelowcode:
publicc
lassItem{
String
birdListName;
int
birdListImage;
public
I
tem (S
tring birdName ,int
birdImage)
{
this
.b
irdListImage =birdImage;
this
.b
irdListName =b
irdName;
}
public
S
tring
getbirdName ()
{
return
birdListName;
}
public
i
ntgetbirdImage ()
{
return
birdListImage;
}
}
Output:
NowruntheAppandyouwillseedifferentbirdimagesinGridView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
110
TextView
InAndroid,TextViewdisplaystexttotheuserandoptionallyallowsthemtoeditit
programmatically.TextViewisacompletetexteditor,howeverbasicclassisconfiguredtonot
alloweditingbutwecaneditit.
ViewistheparentclassofTextView.Beingasubclassofviewthetextviewcomponentcanbe
usedinyourapp’sGUIinsideaViewGroup,orasthecontentviewofanactivity.
WecancreateaTextViewinstancebydeclaringitinsidealayout(XMLfile)orbyinstantiatingit
programmatically(JavaClass).
TextViewcodeinXML:
<TextView
android:id="@+id/simpleTextView"
android
:l
ayout_width
="
wrap_content"
android
:l
ayout_height
="wrap_content"
android
:t
ext
="
AbhiAndroid"/
>
TextViewcodeinJAVA:
TextView
textView=(
TextView
)
findViewById
(R
.i
d
.t
extView
);
textView
.s
etText
("
AbhiAndroid" );
/
/set
text
fortext
view
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
111
AttributesofTextView:
Nowlet’swediscussabouttheattributesthathelpsustoconfigureaTextViewinyourxmlfile.
1.id:idisanattributeusedtouniquelyidentifyatextview.Belowistheexamplecodein
whichwesettheidofatextview.
<TextView
android
:i
d="
@+id/simpleTextView"
android
:l
ayout_width="
wrap_content"
android
:l
ayout_height="wrap_content"
/>
2.gravity:T
hegravityattributeisanoptionalattributewhichisusedtocontrolthealignment
ofthetextlikeleft,right,center,top,bottom,center_vertical,center_horizontaletc.
Belowistheexamplecodewithexplanationincludedinwhichwesetthecenter_horizontal
gravityfortextofaTextView.
<TextView
android
:i
d="
@+id/simpleTextView"
android
:l
ayout_width ="
fill_parent"
android
:l
ayout_height ="wrap_content"
android
:t
ext ="
AbhiAndroid"
android
:t
extSize ="20sp"
android
:g
ravity ="
center_horizontal" />
<
!--
center
horizontal
gravity
-->
3.text:textattributeisusedtosetthetextinatextview.Wecansetthetextinxmlaswellas
inthejavaclass.
Belowistheexamplecodewithexplanationincludedinwhichwesetthetext“AbhiAndroid”in
atextview.
<TextView
android
:i
d="
@+id/simpleTextView"
android
:l
ayout_width ="
wrap_content"
android
:l
ayout_height ="wrap_content"
android
:l
ayout_centerInParent ="
true"
android
:t
extSize ="
25sp"
android
:t
ext ="
AbhiAndroid"/><!--
Display
T
ext
a
s
A
bhiAndroid
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
112
InJavaclass:
Belowistheexamplecodeinwhichwesetthetextinatextviewprogrammaticallymeansin
javaclass.
TextView
textView=(
TextView
)f
indViewById
(R.
id
.t
extView
);
textView
.s
etText
("
AbhiAndroid" );
/
/set
textfortext
view
4.textColor:t extColorattributeisusedtosetthetextcolorofatextview.Colorvalueisin
theformof“#argb”,“#rgb”,“#rrggbb”,or“#aarrggbb”.
Belowistheexamplecodewithexplanationincludedinwhichwesettheredcolorforthe
displayedtext.
<TextView
android
:i
d="
@+id/simpleTextView"
android
:l
ayout_width ="
wrap_content"
android
:l
ayout_height ="wrap_content"
android
:t
ext ="
AbhiAndroid"
android
:l
ayout_centerInParent ="
true"
android
:t
extSize ="
25sp"
android
:t
extColor ="
#f00"/><!--
red
colorf
or
text
view
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
113
InJavaclass:
Belowistheexamplecodeinwhichwesetthetextcolorofatextviewprogrammaticallymeans
injavaclass.
TextView
textView=
(
TextView
)f
indViewById
(R.
id
.t
extView
);
textView
.s
etTextColor(C
olor
.R
ED
);
/
/set
redcolorfor
textview
5.textSize:textSizeattributeisusedtosetthesizeoftextofatextview.Wecansetthetext
sizeinsp(scaleindependentpixel)ordp(densitypixel).
Belowistheexamplecodeinwhichwesetthe20spsizeforthetextofatextview.
<TextView
a
ndroid
:i
d
="
@+id/simpleTextView"
a
ndroid
:l
ayout_width="
wrap_content"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:t
ext="
AbhiAndroid"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:t
extSize="
40sp"/
><!--
Set
size-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
114
InJavaclass:
Belowistheexamplecodeinwhichwesetthetextsizeofatextviewprogrammaticallymeans
injavaclass.
TextView
textView=
(
TextView
)f
indViewById
(R.
id
.t
extView
);
textView
.s
etTextSize
(20
);
/
/set
20sp
size
oftext
6.textStyle:textStyleattributeisusedtosetthetextstyleofatextview.Thepossibletext
stylesarebold,italicandnormal. Ifweneedtousetwoormorestylesforatextviewthen“|”
operatorisusedforthat.
Belowistheexamplecodewithexplanationincludedinwhichwe settheboldanditalictext
stylesfortext.
<TextView
a
ndroid
:i
d
="
@+id/simpleTextView"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext="
AbhiAndroid"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:t
extSize="
40sp"
a
ndroid
:t
extStyle="bold|italic"/><!--
bolda
nd
italic
text
style
of
text
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
115
7.background:backgroundattributeisusedtosetthebackgroundofatextview.Wecanseta
colororadrawableinthebackgroundofatextview.
8.padding:p
addingattributeisusedtosetthepaddingfromleft,right,toporbottom.In
aboveexamplecodeofbackgroundwealsosetthe10dppaddingfromalltheside’softextview.
Belowistheexamplecodewithexplanationincludedinwhichwesettheblackcolorforthe
background,whitecolorforthedisplayedtextandset10dppaddingfromalltheside’sfortext
view.
<TextView
android
:i
d="
@+id/simpleTextView"
android
:l
ayout_width ="
wrap_content"
android
:l
ayout_height ="wrap_content"
android
:t
ext ="
AbhiAndroid"
android
:l
ayout_centerInParent ="
true"
android
:t
extSize ="40sp"
android
:p
adding ="
10dp"
android
:t
extColor ="
#fff"
android
:b
ackground ="#000"/>
<
!--red
colorf
or
background
of
text
view
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
116
InJavaclass:
Belowistheexamplecodeinwhichwesetthebackgroundcolorofatextviewprogrammatically
meansinjavaclass.
TextView
textView=
(
TextView
)f
indViewById(R
.i
d
.t
extView
);
textView
.s
etBackgroundColor(C
olor
.B
LACK
);
//set background
color
ExampleofTextView:
BelowistheexampleofTextViewinwhichwedisplayatextviewandsetthetextinxmlfileand
thenchangethetextonbuttonclickeventprogrammatically.Belowisthefinaloutputand
code:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
117
Step1:C
reateanewprojectandnameittextViewExample.
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
.F
ill
the
formsa
nd
click"
Finish"
button.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
118
Step2:O
penres->layout->xml(or)activity_main.xmlandaddfollowingcode.Herewewill
createabuttonandatextviewinRelativeLayout.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools="
http://schemas.android.com/tools"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop ="
@dimen/activity_vertical_margin"
t
ools
:c
ontext=".MainActivity">
<
TextView
a
ndroid:i
d="
@+id/simpleTextView"
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:l
ayout_centerHorizontal ="true"
a
ndroid:t
ext ="
Before Clicking"
a
ndroid:t
extColor ="#f00"
a
ndroid:t
extSize ="
25sp"
a
ndroid:t
extStyle ="bold|italic"
a
ndroid:l
ayout_marginTop ="
50dp"/>
<
Button
a
ndroid:i
d="
@+id/btnChangeText"
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:l
ayout_centerInParent ="
true"
a
ndroid:b
ackground ="#f00"
a
ndroid:p
adding ="10dp"
a
ndroid:t
ext ="
Change Text"
a
ndroid:t
extColor ="#fff"
a
ndroid:t
extStyle ="bold" /
>
</RelativeLayout>
Step3:Openapp->java->packageandopenMainActivity.javaandaddthefollowingcode.
HerewewillchangethetextofTextViewaftertheuserclickonButton.
package
example
.abhiandriod .t
extviewexample;
import
android.g
raphics .Color;
import
android.s
upport .v
7.app
.A
ppCompatActivity;
import
android.o
s.B
undle;
import
android.v
iew .M
enu;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
119
importandroid .v
iew.MenuItem;
importandroid .v
iew.View;
importandroid .w
idget .B
utton;
importandroid .w
idget .T
extView;
publicclass
MainActivity extends A
ppCompatActivity {
@Override
protected
void
onCreate (B
undle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout.activity_main );
//set the layout
final
TextView simpleTextView= (T
extView )findViewById (R
.i
d.s
impleTextView
);/
/get
the
id for
TextView
Button
changeText= (
Button )
findViewById (R
.i
d.b
tnChangeText );/
/get
the
id
for
button
c
hangeText .s
etOnClickListener (newV
iew .O
nClickListener ()
{
@Override
public v
oid
onClick (View
view ){
s
impleTextView .s
etText ("
After Clicking" );/
/set
the text
after
clicking
button
}
});
}
}
Output:
NowruntheappinEmulatorandclickonthebutton.Youwillseetextwillchange“After
Clicking”.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
120
ScrollView
InandroidScrollViewcanholdonlyonedirectchild.Thismeansthat,ifyouhavecomplex
layoutwithmoreviews(Buttons,TextViewsoranyotherview)thenyoumustenclosethem
insideanotherstandardlayoutlikeTableLayout,RelativeLayoutorLinearLayout.Youcan
specifylayout_widthandlayout_heighttoadjustwidthandheightofscreen.Youcanspecify
heightandwidthindp(densitypixel)orpx(pixel).Thenafterenclosingtheminastandard
layout,enclosethewholelayoutinScrollViewtomakealltheelementorviewsscrollable.
ScrollViewinAndroidStudioDesign:I tispresentinsideContainers>>ScrollViewor
HorizontalScrollView
ImportantNote1:W
eneveruseaScrollViewwithaListViewbecauseListViewisdefault
scrollable(i.e.verticalscrollable).Moreimportantly,doingthisaffectsalloftheimportant
optimizationsinaListViewfordealingwithlargelists(listitems).Justbecauseiteffectively
forcestheListViewtodisplayitsentirelistofitemstofilluptheinfinitecontainersuppliedby
aScrollViewsowedon’tuseitwithListView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
121
ImportantNote2:I nandroiddefaultScrollViewisusedtoscrolltheitemsinvertical
directionandifyouwanttoscrolltheitemshorizontallythenyouneedtoimplement
horizontalScrollView.
ScrollViewSyntax:
<ScrollView
android
:i
d="
@+id/scrollView"
android
:l
ayout_width="
fill_parent"
android
:l
ayout_height="fill_parent">
<!--
addchild
view'shere
-->
</ScrollView>
HereishowScrollViewlooksinAndroid:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
122
HorizontalScrollView:
Inandroid,Youcanscrolltheelementsorviewsinbothverticalandhorizontaldirections.To
scrollinVerticalwesimplyuseScrollViewasweshowninthepreviouscodeofthisarticleand
toscrollinhorizontaldirectionweneedtouseHorizontalScrollview.
BelowisHorizontalScrollViewsyntaxinAndroidis:
<HorizontalScrollView
android
:i
d="
@+id/horizontalscrollView"
android
:l
ayout_width="
fill_parent"
android
:l
ayout_height="fill_parent">
<--
addchild
view's
here -->
</HorizontalScrollView
>
AttributesOfScrollView:
ScrollViewandHorizontalScrollViewhassameattributes,theonlydifferenceisscrollView
scrollthechilditemsinverticaldirectionwhilehorizontalscrollviewscrollthechilditemsin
horizontaldirection.
Nowlet’swediscussabouttheattributesthathelpsustoconfigureaScrollViewanditschild
controls.SomeofthemostimportantattributesyouwillusewithScrollViewinclude:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
123
1.id:I nandroid,idattributeisusedtouniquelyidentifyaScrollView.
Belowisidattribute’sexamplecodewithexplanationincluded.
<ScrollView
android
:i
d
="
@+id/scrollView"
android
:l
ayout_width
="
fill_parent"
android
:l
ayout_height
="fill_parent"
/>
2.scrollbars:Inandroid,scrollbarsattributeisusedtoshowthescrollbarsinhorizontalor
verticaldirection.ThepossibleValueofscrollbarsisvertical,horizontalornone.Bydefault
scrollbarsisshowninverticaldirectioninscrollViewandinhorizontaldirectionin
HorizontalScrollView.
Belowisscrollbarsattribute’sexamplecodeinwhichwesetthescrollbarsinverticaldirection.
<
HorizontalScrollView
android
:l
ayout_width="
fill_parent"
android
:l
ayout_height="fill_parent"
android
:s
crollbars
="
vertical" /><!--
scrollbarsi
n
vertical
direction
-->
ExampleofScrollViewInAndroidStudio:
Example1:Inthisexamplewewilluse10buttonandscrollthemusingScrollViewinvertical
direction.BelowisthecodeandfinalOutputwewillcreate:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
124
Step1:C
reateanewprojectinAndroidStudioandnameitscrollviewExample.
SelectFile->New->NewProject->AndroidApplicationProject(or)AndroidProject.Fillthe
formsandclick“Finish”button.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
125
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddbelowcode.Hereweare
creatingaRelativeLayouthaving10buttonswhicharenestedinLinearLayoutandthenin
ScrollView.
ImportantNote:RememberScrollViewcanholdonlyonedirectchild.Sowehavetojointly
put10buttonsinsideLinearLayouttomakeitonechild.AndthenweputitinsideScrollView.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns
:t
ools="
http://schemas.android.com/tools"
android
:layout_width ="
match_parent"
android
:layout_height ="match_parent"
tools
:c
ontext=".MainActivity">
<ScrollView
android
:layout_width ="
fill_parent"
android
:layout_height ="fill_parent"
android
:scrollbars="vertical">
<LinearLayout
android
:layout_width ="
fill_parent"
android
:layout_height ="fill_parent"
android
:layout_margin ="20dp"
android
:orientation="vertical">
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
android
:background="#f00"
android
:text
="
Button 1"
android
:textColor="
#fff"
android
:textSize="
20sp" />
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
android
:layout_marginTop ="
20dp"
android
:background="#0f0"
android
:text
="
Button 2"
android
:textColor="
#fff"
android
:textSize="
20sp" />
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
android
:layout_marginTop ="
20dp"
android
:background="#00f"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
126
android
:text
="
Button 3"
android
:textColor
="#fff"
android
:textSize
="20sp" />
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
android
:layout_marginTop ="
20dp"
android
:background="
#ff0"
android
:text
="
Button 4"
android
:textColor
="#fff"
android
:textSize
="20sp" />
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
android
:layout_marginTop ="
20dp"
android
:background="
#f0f"
android
:text
="
Button 5"
android
:textColor
="#fff"
android
:textSize
="20sp" />
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
android
:layout_marginTop ="
20dp"
android
:background="
#f90"
android
:text
="
Button 6"
android
:textColor
="#fff"
android
:textSize
="20sp" />
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
android
:layout_marginTop ="
20dp"
android
:background="
#f00"
android
:text
="
Button 7"
android
:textColor
="#ff9"
android
:textSize
="20sp" />
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
android
:layout_marginTop ="
20dp"
android
:background="
#444"
android
:text
="
Button 8"
android
:textColor
="#fff"
android
:textSize
="20sp" />
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
127
android
:layout_marginTop ="
20dp"
android
:background="#ff002211"
android
:text
="
Button 9"
android
:textColor="
#fff"
android
:textSize="
20sp" />
<Button
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:layout_gravity ="center"
android
:layout_marginTop ="
20dp"
android
:background="#0f0"
android
:text
="
Button 10"
android
:textColor="
#fff"
android
:textSize="
20sp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Step3:N
owOpensrc->package->MainActivity.javaandpastethebelowcode
packagecom.e
xample .g
ourav.scrollviewExample;
import
android .s
upport.v
7.app
.A
ppCompatActivity;
import
android .o
s.B
undle;
publicc
lass M
ainActivity extendsA
ppCompatActivity
{
@Override
protected void
onCreate(Bundle
savedInstanceState)
{
super
.o
nCreate (s
avedInstanceState );
setContentView (R
.l
ayout
.activity_main );
}
}
Step4:N
owopenmanifest.xmlandpastethebelowcode
<?
xml
version
="1.0"
encoding
="
utf-8"
?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package
="
com.example.gourav.scrollviewExample"
>
<application
android
:a
llowBackup="
true"
android
:i
con
="
@mipmap/ic_launcher"
android
:l
abel
="@string/app_name"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
128
android
:t
heme ="@style/AppTheme"
>
<activity
android
:n
ame ="
.MainActivity"
android
:l
abel ="@string/app_name"
>
<intent-filter>
<action
a
ndroid:name ="
android.intent.action.MAIN"/
>
<categoryandroid:name ="
android.intent.category.LAUNCHER"
/
>
</intent-filter>
</activity>
</application>
</manifest>
Step5:Lastlyopenres->values->strings.xmlandpastethebelowcode
<resources>
<string
n
ame
="app_name"
>S
crollViewExample
</string>
<string
n
ame
="hello_world"
>H
ello
world!
</string>
<string
n
ame
="action_settings"
>S
ettings
</string>
</resources>
Output:
NowruntheAppinEmulator/AVDorinrealdevice.Youwillseethe10buttonswhichcanbe
scrollableinverticaldirection.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
129
Spinner
InAndroid,Spinnerprovidesaquickwaytoselectonevaluefromasetofvalues.Android
spinnersarenothingbutthedropdown-listseeninotherprogramminglanguages.Inadefault
state,aspinnershowsitscurrentlyselectedvalue.Itprovidesaeasywaytoselectavaluefroma
listofvalues.
InSimpleWordswecansaythataspinnerislikeacomboboxofAWTorswingwherewecan
selectaparticularitemfromalistofitems.SpinnerisasubclassofAsbSpinnerclass.
ImportantNote:S pinnerisassociatedwithAdapterviewsotofillthedatainspinnerwe
needtouseoneoftheAdapterclass.
HereistheXMLbasiccodeforSpinner:
<Spinner
android
:i
d
="
@+id/simpleSpinner"
android
:l
ayout_width
="
fill_parent"
android
:l
ayout_height
="wrap_content"
/
>
ImportantNote:Tofillthedatainaspinnerweneedtoimplementanadapterclass.A
spinnerismainlyusedtodisplayonlytextfieldsowecanimplementArrayAdapterforthat.We
canalsouseBaseAdapterandothercustomadapterstodisplayaspinnerwithmorecustomize
list.Supposeifweneedtodisplayatextviewandaimageviewinspinneritemlistthenarray
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
130
adapterisnotenoughforthat.Herewehavetoimplementcustomadapterinourclass.Below
imageofSpinnerandCustomSpinnerwillmakeitmoreclear.
ArraryAdapter:
AnadapterisabridgebetweenUIcomponentanddatasourcethathelpsustofilldatainUI
component.Itholdsthedataandsendthedatatoadapterviewthenviewcantakesthedata
fromtheadapterviewandshowsthedataondifferentviewslikeaslistview,gridview,spinner.
Wheneveryouhavealistofsingleitemswhichisbackedbyanarray,youcanuseArrayAdapter.
HereiscodeofArrayAdapterinAndroid:
ArrayAdapter
(Context
context
,i
nt
resource
,i
nt
textViewResourceId
,
T[]
objects)
ExampleofSpinnerInAndroidStudio:
Example1:Belowistheexampleinwhichwedisplayalistofbanknamesinaspinnerand
wheneveryouselectanitemthevaluewillbedisplayedusingtoastonMobilescreen.Belowis
thefinaloutputandcode:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
131
Step1:CreateanewprojectinAndroidStudioandnameitSpinnerExample.
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
-
>.
F
ill
the
formsa
nd
click"
Finish"
button.
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode.Herewe
willcreateaSpinnerinsideRelativeLayout.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns
:t
ools="
http://schemas.android.com/tools"
android
:l
ayout_width ="
match_parent"
android
:l
ayout_height ="match_parent"
android
:p
addingBottom ="@dimen/activity_vertical_margin"
android
:p
addingLeft="
@dimen/activity_horizontal_margin"
android
:p
addingRight ="
@dimen/activity_horizontal_margin"
android
:p
addingTop="
@dimen/activity_vertical_margin"
tools
:c
ontext="
.MainActivity">
<Spinner
android
:i
d
="
@+id/simpleSpinner"
android
:l
ayout_width ="
wrap_content"
android
:l
ayout_height ="wrap_content"
android
:l
ayout_centerHorizontal ="true"
android
:l
ayout_marginTop ="
100dp"/
>
</RelativeLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
132
Step3:Nowopenapp->java->package->MainActivity.javaandaddthefollowingcode.Here
wewilluseArrayAdaptertofillthedatainSpinner.AlsoweareusingToasttodisplaywhenthe
iteminSpinnerisselected.
package example .abhiandriod .spinnerexample;
import
android .s
upport .v
7.app.A
ppCompatActivity;
import
android .o
s.B
undle;
import
android .v
iew .V
iew;
import
android .w
idget .A
dapterView;
import
android .w
idget .A
rrayAdapter;
import
android .w
idget .S
pinner;
import
android .w
idget .T
oast;
public c
lass M
ainActivity extends A
ppCompatActivity i
mplements
AdapterView .O
nItemSelectedListener{
String[]
bankNames ={"BOI" ,"SBI" ,"
HDFC" ,"PNB" ,"OBC" };
@Override
protected void
onCreate (B
undle savedInstanceState ){
super.onCreate (s
avedInstanceState );
setContentView (R
.l
ayout .activity_main );
//Getting theinstance ofSpinner and applying OnItemSelectedListener onit
Spinner spin= (
S
pinner )findViewById (R
.i
d.s
impleSpinner );
spin.s
etOnItemSelectedListener (this );
//Creating theArrayAdapter instance having the bank namelist
ArrayAdapter aa=newA
rrayAdapter (this ,android .R.l
ayout .s
imple_spinner_item ,b
ankNames );
aa
.s
etDropDownViewResource (a
ndroid .R.
layout .simple_spinner_dropdown_item );
//Setting theArrayAdapter data on the Spinner
spin.s
etAdapter (aa
);
}
//Performing action onItemSelected and onNothing selected
@Override
public v
oid
onItemSelected (A
dapterView <?>
arg0 ,V iew arg1
,int
position
,l
ong
id)
{
Toast.makeText (g
etApplicationContext (),bankNames [p
osition ],
T
oast.L
ENGTH_LONG ).
show ();
}
@Override
public v
oid
onNothingSelected (A
dapterView <?>
arg0 ){
//
TODO Auto-generated method stub
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
133
Output:
NowtheruntheprograminEmulatorandyouwillseeoptionstochooseamongbanknames
presentinsidedropdownlist.YouwillalsoseeToastmessagedisplayingonthescreenwhen
youwillselecttheparticularbank.
CustomSpinner:
CustomSpinnerisusedtodisplayaspinneritemwithimage,textetc(i.e.creatingmorecustom
listitem).ItisachievedinAndroidusingcustomadapterlikebaseadapter.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
134
EditText
InAndroid,EditTextisastandardentrywidgetinandroidapps.ItisanoverlayoverTextView
thatconfiguresitselftobeeditable.EditTextisasubclassofTextViewwithtextediting
operations.WeoftenuseEditTextinourapplicationsinordertoprovideaninputortextfield,
especiallyinforms.ThemostsimpleexampleofEditTextisLoginorSign-inform.
TextFieldsinAndroidStudioarebasicallyEditText:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
135
ImportantNote:AnEditTextissimplyathinextensionofaTextView.AnEditTextinherits
allthepropertiesofaTextView.
EditTextCode:
WecancreateaEditTextinstancebydeclaringitinsidealayout(XMLfile)orbyinstantiatingit
programmatically(i.e.inJavaClass).
EditTextcodeinXML:
<EditText
android
:i
d="
@+id/simpleEditText"
android
:l
ayout_height="wrap_content"
android
:l
ayout_width="
match_parent"/>
Retrieving/GettingtheValueFromEditTextInJavaClass:
BelowistheexamplecodeofEditTextinwhichweretrievethevaluefromaEditTextinJava
class.Wehaveusedthiscodeintheexampleyouwillfindattheendofthispost.
EditText
simpleEditText=(
EditText
)
findViewById(R
.i
d
.s
impleEditText
);
String
editTextValue=
simpleEditText .g
etText
().
toString ();
AttributesofEditText:
Nowlet’s wediscussfewattributesthathelpsustoconfigureaEditTextinyourxml.
1.id:idisanattributeusedtouniquelyidentifyatextEditText.Belowistheexamplecodein
whichwesettheidofaedittext.
<EditText
android
:i
d="
@+id/simpleEditText"
android
:l
ayout_height="wrap_content"
android
:l
ayout_width="
match_parent"/>
2.gravity:Thegravityattributeisanoptionalattributewhichisusedtocontrolthealignment
ofthetextlikeleft,right,center,top,bottom,center_vertical,center_horizontaletc.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
136
Belowistheexamplecodewithexplanationincludedinwhichwesettherightgravityfortextof
aEditText.
<EditText
a
ndroid
:i
d
="
@+id/simpleEditText"
a
ndroid
:l
ayout_width="fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:t
ext="
Enter
Email"
a
ndroid
:g
ravity="
right"/><!--
gravity
of
a
edit
text
-->
3.text:textattributeisusedtosetthetextinaEditText.Wecansetthetextinxmlaswellas
inthejavaclass.
Belowistheexamplecodeinwhichwesetthetext“Username”inaedittext.
<EditText
a
ndroid
:i
d
="
@+id/simpleEditText"
a
ndroid
:l
ayout_width="
fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:l
ayout_centerInParent ="true"
a
ndroid
:t
ext="
Username"/><!--
set
textin
edit
text
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
137
SettingtextinEditTextInJavaclass:
Belowistheexamplecodeinwhichwesetthetextina textviewprogrammaticallymeansin
javaclass.
EditText
editText=(
EditText
)findViewById
(R.
id
.s
impleEditText
);
editText
.s
etText
("
Username" );
//setthe
textinedit
text
4.hint:h
intisanattributeusedtosetthehinti.e.whatyouwantusertoenterinthisedit
text.Wheneveruserstarttotypeinedittextthehintwillautomaticallydisappear.
Belowistheexamplecodewithexplanationinwhichwesetthehintofaedittext.
<EditText
a
ndroid
:i
d
="
@+id/simpleEditText"
a
ndroid
:l
ayout_width="fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:h
int="
Enter
YourName
Here"/
><!--
display
the
hint
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
138
SettinghintinEditTextInJavaclass:
Belowistheexamplecodeinwhichwesetthetextina textviewprogrammaticallymeansin
javaclass.
EditText
editText=(
EditText
)f
indViewById(R
.i
d
.s
impleEditText
);
editText
.s
etHint
("
Enter Your
Name
Here"
);
//display the
hint
5.textColor:textColorattributeisusedtosetthetextcolorofatextedittext.Colorvalueis
intheformof“#argb”,“#rgb”,“#rrggbb”,or“#aarrggbb”.
Belowistheexamplecodewithexplanationincludedinwhichwesettheredcolorforthe
displayedtextofaedittext.
<EditText
a
ndroid
:i
d
="
@+id/simpleEditText"
a
ndroid
:l
ayout_width
="fill_parent"
a
ndroid
:l
ayout_height
="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
139
a
ndroid
:l
ayout_centerInParent="
true"
a
ndroid
:t
ext
="Password"
a
ndroid
:t
extColor="
#f00"
/><!--
set
the
red
text
color
-->
SettingtextColorinEditTextInJavaclass:
Belowistheexamplecodeinwhichwesetthetextcolorofaedittextprogrammaticallymeans
injavaclass.
EditText
simpleEditText
=(
EditText
)f
indViewById(R
.i
d
.s
impleEditText);
simpleEditText
.s
etTextColor
(C
olor
.R
ED
);
//set
the redtext
color
6.textColorHint:t extColorHintisanattributeusedtosetthecolorofdisplayedhint.
Belowistheexamplecodewithexplanationincludedinwhichwesetthegreencolorfor
displayedhintofaedittext.
<EditText
a
ndroid
:i
d
="
@+id/simpleEditText"
a
ndroid
:l
ayout_width="fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:h
int="
Enter
YourNameHere"
a
ndroid
:t
extColorHint="#0f0"
/><!--set
the
hint
color
green
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
140
SettingtextColorHintinEditTextInJavaclass:
Belowistheexamplecodeinwhichwesetthehintcolorofaedittextprogrammaticallymeans
injavaclass.
EditText
simpleEditText
=(
EditText
)f
indViewById(R
.i
d
.s
impleEditText
);
simpleEditText
.s
etHintTextColor
(C
olor
.g
reen
(0
));
//setthe
green
hintcolor
7.textSize:textSizeattributeisusedtosetthesizeoftextofaedittext.Wecansetthetext
sizeinsp(scaleindependentpixel)ordp(densitypixel).
Belowistheexamplecodeinwhichwesetthe25spsizeforthetextofaedittext.
<EditText
a
ndroid
:i
d
="
@+id/simpleEditText"
a
ndroid
:l
ayout_width
="fill_parent"
a
ndroid
:l
ayout_height
="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
141
a
ndroid
:l
ayout_centerInParent="
true"
a
ndroid
:t
ext
="AbhiAndroid"
a
ndroid
:t
extSize="
25sp"
/
><!--
set
2
5sp
text
size
-->
SettingtextSizeinEditTextinJavaclass:
Belowistheexamplecodeinwhichwesetthetextsizeofaedittextprogrammaticallymeansin
javaclass.
EditText
simpleEditText
=(
EditText
)f
indViewById(R
.i
d
.s
impleEditText
);
simpleEditText
.s
etTextSize
(2
5
);
//set
size
of
text
8.textStyle:t extStyleattributeisusedtosetthetextstyleofaedittext.Thepossibletext
stylesarebold,italicandnormal.Ifweneedtousetwoormorestylesforaedittextthen“|”
operatorisusedforthat.
Belowistheexamplecodewithexplanationincluded,inwhichwesettheboldanditalictext
stylesfortext.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
142
<EditText
a
ndroid
:i
d
="
@+id/simpleEditText"
a
ndroid
:l
ayout_width ="fill_parent"
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:t
ext="
Email"
a
ndroid
:t
extSize="
25sp"
a
ndroid
:t
extStyle="bold|italic"/><!--
set
bolda
nd
italic
text
style
-->
9.background:backgroundattributeisusedtosetthebackgroundofaedittext.Wecanseta
colororadrawableinthebackgroundofaedittext.
Belowistheexamplecodewithexplanationincludedinwhichwesettheblackcolorforthe
background,whitecolorforthedisplayedhintandset10dppaddingfromalltheside’sforedit
text.
<EditText
a
ndroid
:i
d
="
@+id/simpleEditText"
a
ndroid
:l
ayout_width ="
fill_parent"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:h
int="
Enter YourNameHere"
a
ndroid
:p
adding="
15dp"
a
ndroid
:t
extColorHint ="#fff"
a
ndroid
:t
extStyle ="
bold|italic"
a
ndroid
:b
ackground ="
#000" /><!--set
background
color
black
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
143
SettingBackgroundinEditTextInJavaclass:
Belowistheexamplecodeinwhichwesetthebackgroundcolorofaedittextprogrammatically
meansinjavaclass.
EditText
simpleEditText
=(
EditText
)f
indViewById(R
.i
d
.s
impleEditText);
simpleEditText
.s
etBackgroundColor
(C
olor
.B
LACK
);//set black
backgroundcolor
10.padding:paddingattributeisusedtosetthepaddingfromleft,right,toporbottom.In
aboveexamplecodeofbackgroundwealsosetthe10dppaddingfromalltheside’sofedittext.
ExampleI–EditTextinAndroidStudio
Belowistheexampleofedittextinwhichwegetthevaluefrommultipleedittextsandon
buttonclickeventtheToastwillshowthedatadefinedinEdittext.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
144
Step1:CreateanewprojectinAndroidStudioandnameitEditTextExample.
Step2:N
owOpenres->layout->xml(or)activity_main.xmlandaddfollowingcode.Inthis
codewehaveaddedmultipleedittextandabuttonwithonclickfunctionality.
<?
xml
version
="1.0"encoding ="
utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools="http://schemas.android.com/tools"
a
ndroid
:i
d="
@+id/activity_main"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop ="
@dimen/activity_vertical_margin"
t
ools
:c
ontext ="
com.example.edittextexample.MainActivity">
<
EditText
a
ndroid:id
="@+id/editText1"
a
ndroid:layout_width ="
wrap_content"
a
ndroid:layout_height ="wrap_content"
a
ndroid:layout_alignParentLeft ="true"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
145
a
ndroid
:l
ayout_alignParentStart ="true"
a
ndroid
:l
ayout_alignParentTop ="
true"
a
ndroid
:l
ayout_marginLeft ="50dp"
a
ndroid
:l
ayout_marginStart ="50dp"
a
ndroid
:l
ayout_marginTop ="
24dp"
a
ndroid
:e
ms
="
10"
a
ndroid
:h
int
="@string/name"
a
ndroid
:i
nputType ="
textPersonName"
a
ndroid
:s
electAllOnFocus ="
true" /
>
<
EditText
a
ndroid
:i
d
="
@+id/editText2"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_alignLeft ="
@+id/editText1"
a
ndroid
:l
ayout_alignStart ="@+id/editText1"
a
ndroid
:l
ayout_below ="
@+id/editText1"
a
ndroid
:l
ayout_marginTop ="
19dp"
a
ndroid
:e
ms
="
10"
a
ndroid
:h
int="
@string/password_0_9"
a
ndroid
:i
nputType ="
numberPassword" /
>
<
EditText
a
ndroid
:i
d
="
@+id/editText3"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_alignLeft ="
@+id/editText2"
a
ndroid
:l
ayout_alignStart ="@+id/editText2"
a
ndroid
:l
ayout_below ="
@+id/editText2"
a
ndroid
:l
ayout_marginTop ="
12dp"
a
ndroid
:e
ms
="
10"
a
ndroid
:h
int="
@string/e_mail"
a
ndroid
:i
nputType ="
textEmailAddress" /
>
<
EditText
a
ndroid
:i
d
="
@+id/editText4"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_alignLeft ="
@+id/editText3"
a
ndroid
:l
ayout_alignStart ="@+id/editText3"
a
ndroid
:l
ayout_below ="
@+id/editText3"
a
ndroid
:l
ayout_marginTop ="
18dp"
a
ndroid
:e
ms
="
10"
a
ndroid
:h
int="
@string/date"
a
ndroid
:i
nputType ="
date"/
>
<
EditText
a
ndroid
:i
d
="
@+id/editText5"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_alignLeft ="
@+id/editText4"
a
ndroid
:l
ayout_alignStart ="@+id/editText4"
a
ndroid
:l
ayout_below ="
@+id/editText4"
a
ndroid
:l
ayout_marginTop ="
18dp"
a
ndroid
:e
ms
="
10"
a
ndroid
:h
int="
@string/contact_number"
a
ndroid
:i
nputType ="
phone"/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
146
<
Button
a
ndroid
:i
d="
@+id/button"
s
tyle
="
@android:style/Widget.Button"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_alignParentLeft ="
true"
a
ndroid
:l
ayout_alignParentStart ="true"
a
ndroid
:l
ayout_below ="
@+id/editText5"
a
ndroid
:l
ayout_marginTop ="
62dp"
a
ndroid
:t
ext ="
@string/submit"
a
ndroid
:t
extSize ="
16sp"
a
ndroid
:t
extStyle ="normal|bold" />
</RelativeLayout>
Step3:N
owopenapp->java->package->MainActivity.javaandaddthebelowcode.
Inthiswejustfetchthetextfromtheedittext,furtherwiththebuttonclickeventatoastwill
showthetextfetchedbefore.
packagecom.e
xample .edittextexample;
import
android .s
upport .v
7.app
.AppCompatActivity;
import
android .o
s.Bundle;
import
android .v
iew .View;
import
android .w
idget .Button;
import
android .w
idget .EditText;
import
android .w
idget .Toast;
publicc
lass MainActivity extends A
ppCompatActivity
{
Button
submit;
EditText
name, password ,email,contact ,date;
@Override
protected
void onCreate (B
undle savedInstanceState ){
super
.onCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .activity_main );
n
ame= (
EditText )findViewById (R.
id
.editText1 );
p
assword= (E
ditText )findViewById (R.i
d
.editText2 );
e
mail= (E
ditText )findViewById (R
.i
d.editText3 );
d
ate= (
EditText )findViewById (R.
id
.editText4 );
c
ontact= (EditText )findViewById (R
.id
.e
ditText5 );
s
ubmit= (Button ) findViewById (R.
id
.button );
s
ubmit .s
etOnClickListener (n
ew V
iew .OnClickListener ()
{
@Override
public voidonClick (Viewv)
{
if
(n
ame .g
etText ().toString (). isEmpty ()
||
password .getText (). toString ().isEmpty ()||
email .getText ().toString ().isEmpty
()
|
|
date
.getText (). toString ().isEmpty ()
||
contact .getText (). toString ().isEmpty ())
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
147
Toast .m
akeText (g
etApplicationContext (),"
Enterthe
Data"
,
Toast
.LENGTH_SHORT ).
show();
}e
lse
{
Toast .m
akeText (g
etApplicationContext (),"
Name
- "+
name
.getText
(). toString()+"
\n"
+
"Password- "
+
password .g
etText().
toString
()
+"
\n"+"
E-Mail
- "
+email
.g
etText().toString
()
+
"\n"
+
"Date- "
+
date.getText().toString ()
+"
\n"+"
Contact
- "+
contact.g
etText().
toString(),
Toast
.LENGTH_SHORT ).
show();
}
}
});
}
}
Output:
NowstarttheAVDinEmulatorandruntheApp.Youwillseescreenaskingyoutofillthedatain
requiredfieldslikename,password(numeric),email,date,contactnumber.Enterdataandclick
onbutton.YouwillseethedataenteredwillbedisplayedasToastonscreen.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
148
Button
InAndroid,Buttonrepresentsapushbutton.APushbuttonscanbeclicked,orpressedbythe
usertoperformanaction.Therearedifferenttypesofbuttonsusedinandroidsuchas
CompoundButton,ToggleButton,RadioButton.
ButtonisasubclassofTextViewclassandcompoundbuttonisthesubclassofButtonclass.O
n
abuttonwecanperformdifferentactionsoreventslikeclickevent,pressedevent,touch
eventetc.
AndroidbuttonsareGUIcomponentswhicharesensibletotaps(clicks)bytheuser.Whenthe
usertaps/clicksonbuttoninanAndroidapp,theappcanrespondtotheclick/tap.These
buttonscanbedividedintotwocategories:thefirstisButtonswithtexton,andsecondis
buttonswithanimageon.Abuttonwithimagesoncancontainbothanimageandatext.
AndroidbuttonswithimagesonarealsocalledImageButton.
ButtoncodeinXML:
ThebelowcodewillcreateButtonandwrite“AbhiAndroid”textonit.
<Button
android
:id
="
@+id/simpleButton"
android
:layout_width ="
wrap_content"
android
:layout_height ="wrap_content"
android
:text="
Abhi
Android" />
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
149
AttributesofButtoninAndroid:Nowlet’s wediscusssomeimportantattributesthat
helpsustoconfigureaButtoninyourxmlfile(layout).
1.id:idisanattributeusedtouniquelyidentifyatextButton.Belowistheexamplecodein
whichwesettheidofaButton.
<Button
android
:id
="
@+id/simpleButton"
android
:layout_width ="
wrap_content"
android
:layout_height ="wrap_content"
android
:text="
Abhi
Android" />
2.gravity:T
hegravityattributeisanoptionalattributewhichisusedtocontrolthealignment
ofthetextlikeleft,right,center,top,bottom,center_vertical,center_horizontaletc.
Belowistheexamplecodewithexplanationincludedinwhichwesettherightandcenter
verticalgravityfortextofaButton.
<Button
android
:id
="
@+id/simpleButton"
android
:layout_width ="
fill_parent"
android
:layout_height ="wrap_content"
android
:text="
Abhi
Android"
android
:layout_centerInParent ="
true"
android
:gravity="
right|center_vertical" /><!--
set
the
gravity
of
button
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
150
3.text:textattributeisusedtosetthetextinaButton.Wecansetthetextinxmlaswellasin
thejavaclass.
Belowistheexamplecodewithexplanationincludedinwhichwesetthetext“Learning
Android@AbhiAndroid”inaButton.
<Button
a
ndroid
:i
d
="
@+id/simpleButton"
a
ndroid
:l
ayout_width="fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:t
ext="
Learn
Android@
AbhiAndroid"
/><!--
display
text
on
button
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
151
SettingTextUsingJavaclass:
BelowistheexamplecodeinwhichwesetthetextonButtonprogrammaticallymeansinjava
class.Theoutputwillbesameastheabove.
Button
button
=(B
utton
)
findViewById
(R
.i
d
.s
impleButton);
button
.s
etText
("
LearnAndroid
@
AbhiAndroid" );
//set
the
text
on
button
4.textColor:textColorattributeisusedtosetthetextcolorofaButton.Colorvalueisinthe
formof“#argb”,“#rgb”,“#rrggbb”,or“#aarrggbb”.
Belowistheexamplecodewithexplanationincludedinwhichwesettheredcolorforthe
displayedtextofaButton.
<Button
android
:id
="
@+id/simpleButton"
android
:layout_width="
fill_parent"
android
:layout_height="wrap_content"
android
:layout_centerInParent ="
true"
android
:text="
AbhiAndroid"
android
:textColor="
#f00"/><!--
red
colorf
or
the
text
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
152
SettingTextColorOnButtonInsideJavaclass:
BelowistheexamplecodeinwhichwesetthetextcolorofaButtonprogrammaticallymeansin
javaclass.
Button
simpleButton=(
Button
)
findViewById
(R
.i
d
.s
impleButton);
simpleButton
.setTextColor
(C
olor
.R
ED
);
//setthered
color
for
the
text
5.textSize:t extSizeattributeisusedtosetthesizeofthetextonButton.Wecansetthetext
sizeinsp(scaleindependentpixel)ordp(densitypixel).
Belowistheexamplecodeinwhichwesetthe25spsizeforthetextofaButton.
<Button
android
:id
="
@+id/simpleButton"
android
:layout_width="
fill_parent"
android
:layout_height="wrap_content"
android
:layout_centerInParent ="
true"
android
:text="
AbhiAndroid"
android
:textSize="
25sp"/
><!--
25sp
text
size
-->
SettingtextSizeInJavaclass:
BelowistheexamplecodeinwhichwesetthetextsizeofaButtonprogrammaticallymeansin
javaclass.
Button
simpleButton=(
Button
)f
indViewById(R
.i
d.s
impleButton
);
simpleButton
.setTextSize
(2
5
);
//set
the
text size
of
button
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
153
6.textStyle:t extStyleattributeisusedtosetthetextstyleofaButton.Thepossibletext
stylesarebold,italicandnormal.IfweneedtousetwoormorestylesforaButtonthen“|”
operatorisusedforthat.
Belowistheexamplecodewithexplanationincluded,inwhichwesettheboldanditalictext
stylesfortextofabutton.
<Button
a
ndroid
:i
d
="
@+id/simpleButton"
a
ndroid
:l
ayout_width ="
fill_parent"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:t
ext="
AbhiAndroid"
a
ndroid
:t
extSize="
20sp"
a
ndroid
:t
extStyle="bold|italic" /><!--
bolda
nd
italic
text
style
-->
7.background:backgroundattributeisusedtosetthebackgroundofaButton.Wecanseta
colororadrawableinthebackgroundofaButton.
Belowistheexamplecodeinwhichwesetthegrencolorforthebackground,Blackcolorforthe
displayedtextandset15dppaddingfromalltheside’sforButton.
<Button
android
:id
="
@+id/simpleButton"
android
:layout_width
="
fill_parent"
android
:layout_height
="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
154
android
:l
ayout_centerInParent ="
true"
android
:t
ext
="
Download"
android
:t
extSize="
20sp"
android
:p
adding
="
15dp"
android
:t
extStyle="
bold|italic"
android
:b
ackground="#147D03"
/
><!--Background
green
color
-->
SettingbackgroundinButtonInJavaclass:
BelowistheexamplecodeinwhichwesetthebackgroundcolorofaButtonprogrammatically
meansinjavaclass.
Button
simpleButton=(
Button
)f
indViewById
(R
.i
d
.s
impleButton
);
simpleButton
.setBackgroundColor
(C
olor
.B
LACK);
//set
the
blackcolor
of
button
background
8.padding:p
addingattributeisusedtosetthepaddingfromleft,right,toporbottom.In
aboveexamplecodeofbackgroundwealsosetthe10dppaddingfromalltheside’sofbutton.
9.drawableBottom:d
rawableBottomisthedrawabletobedrawntothebelowofthetext.
Belowistheexamplecodeinwhichwesettheicontothebelowofthetext.
Makesureyouhaveimagesavedinyourdrawablefoldernameic_launcher.
<Button
a
ndroid
:i
d
="
@+id/simpleButton"
a
ndroid
:l
ayout_width
="fill_parent"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
155
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:b
ackground ="
#147D03"
a
ndroid
:t
ext
="Download Code"
a
ndroid
:t
extSize="20sp"
a
ndroid
:p
adding="
15dp"
a
ndroid
:t
extStyle ="
bold|italic"
a
ndroid
:d
rawableBottom ="@drawable/ic_launcher"
/><!--
image
drawable
on
button
-->
10.drawableTop,drawableRightAnddrawableLeft:J ustliketheaboveattributewecan
drawdrawabletotheleft,rightortopoftext.
IntheBelowexamplewesettheicontotherightofthetext.Inthesamewayyoucandofor
othertwoattributebyyourown:
<Button
android
:i
d
="
@+id/simpleButton"
android
:l
ayout_width ="
fill_parent"
android
:l
ayout_height ="wrap_content"
android
:l
ayout_centerInParent ="
true"
android
:b
ackground ="
#147D03"
android
:t
ext="
Download Code"
android
:t
extSize="20sp"
android
:p
adding="
15dp"
android
:t
extStyle ="
bold|italic"
android
:d
rawableRight ="@drawable/ic_launcher"
/><!--
image
drawable
onR
ight
side
ofT
ext
on
button-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
156
ButtonExampleInAndroidStudio:
Belowistheexampleofbuttoninwhichwedisplaytwobuttonswithdifferentbackgroundand
wheneverauserclickonthebuttonthetextofthebuttonwillbedisplayedinatoast.
Step1:CreateanewprojectinAndroidStudioandnameitButtonExample.
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
a
nd
F
ill
the
formsa
nd
click"
Finish"
button.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
157
Step2:N
owopenres->layout->xml(or)activity_main.xmlandaddfollowingcode.Herewe
aredesigningtheUIoftwobuttoninRelativeLayout.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools
="
http://schemas.android.com/tools"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop ="
@dimen/activity_vertical_margin"
t
ools
:c
ontext="
.MainActivity">
<
Button
a
ndroid
:i
d="@+id/simpleButton1"
a
ndroid
:l
ayout_width ="
fill_parent"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_centerHorizontal ="true"
a
ndroid
:l
ayout_marginTop ="
100dp"
a
ndroid
:b
ackground ="#00f"
a
ndroid
:d
rawableRight ="@drawable/ic_launcher"
a
ndroid
:h
int ="
AbhiAndroid Button1"
a
ndroid
:p
adding ="5dp"
a
ndroid
:t
extColorHint ="#fff"
a
ndroid
:t
extSize ="
20sp"
a
ndroid
:t
extStyle ="bold|italic" /
>
<
Button
a
ndroid
:i
d="@+id/simpleButton2"
a
ndroid
:l
ayout_width ="
fill_parent"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:b
ackground ="#f00"
a
ndroid
:d
rawableLeft ="
@drawable/ic_launcher"
a
ndroid
:h
int ="
AbhiAndroid Button2"
a
ndroid
:p
adding ="5dp"
a
ndroid
:t
extColorHint ="#fff"
a
ndroid
:t
extSize ="
20sp"
a
ndroid
:t
extStyle ="bold|italic" /
>
</RelativeLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
158
Step3:N
owOpen app->package->MainActivity.javaandthefollowingcode.Hereusing
setOnClickListener()methodonbuttonandusingToastwewilldisplaywhichbuttonisclicked
byuser.
packageexample .abhiandriod .b
uttonexample;
import
android .s
upport .v7
.app
.AppCompatActivity;
import
android .o
s.B
undle;
import
android .v
iew .M
enu;
import
android .v
iew .M
enuItem;
import
android .v
iew .V
iew;
import
android .w
idget .Button;
import
android .w
idget .Toast;
publicc
lassMainActivity extends A
ppCompatActivity
{
Button
simpleButton1 ,simpleButton2;
@Override
protected
voidonCreate (B
undle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .a
ctivity_main );
s
impleButton1= (
Button )findViewById (R.
id
.s
impleButton1 );
//get id
of
button
1
s
impleButton2= (
Button )findViewById (R.
id
.s
impleButton2 );
//get id
of
button
2
s
impleButton1 .setOnClickListener (new V
iew .O
nClickListener ()
{
@Override
public void
onClick (View
view){
Toast
.makeText (g
etApplicationContext (), "
Simple
Button 1"
,
Toast
.LENGTH_LONG ).
show ();//display the
text of button1
}
});
s
impleButton2 .setOnClickListener (new V
iew .O
nClickListener ()
{
@Override
public void
onClick (View
view){
Toast
.makeText (g
etApplicationContext (), "
Simple
Button 2"
,
Toast
.LENGTH_LONG ).
show ();//display the
text of button2
}
});
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
159
Output:
NowstarttheAVDinEmulatorandruntheApp.Youwillseetwobutton.Clickonanybutton
andyouwillseethemessageonscreenwhichbuttonisclicked.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
160
ImageView
InAndroid,ImageViewclassisusedtodisplayanimagefileinapplication.Imagefileiseasyto
usebuthardtomasterinAndroid,becauseofthevariousscreensizesinAndroiddevices.An
androidisenrichedwithsomeofthebestUIdesignwidgetsthatallowsustobuildgoodlooking
andattractiveUIbasedapplication.
ImportantNote:I mageViewcomeswithdifferentconfigurationoptionstosupportdifferent
scaletypes.Scaletypeoptionsareusedforscalingtheboundsofanimagetotheboundsofthe
imageview.SomeofthemscaleTypesconfigurationpropertiesarecenter,center_crop,fit_xy,
fitStartetc.
BelowisanImageViewcodeinXML:
Makesuretosavelionimageindrawablefolder
<ImageView
android
:i
d
="
@+id/simpleImageView"
android
:l
ayout_width="
fill_parent"
android
:l
ayout_height="wrap_content"
android
:s
rc
="@drawable/lion"/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
161
AttributesofImageView:
Nowlet’s wediscusssomeimportantattributesthathelpsustoconfigureaImageViewinyour
xmlfile.
1.id:idisanattributeusedtouniquelyidentifyaimageviewinandroid.Belowistheexample
codeinwhichwesettheidofaimageview.
<ImageView
android
:i
d
="
@+id/simpleImageView"
android
:l
ayout_width
="
fill_parent"
android
:l
ayout_height
="wrap_content"
/>
2.src:s rcisanattributeusedtosetasourcefileoryoucansayimageinyourimageviewto
makeyourlayoutattractive.
Belowistheexamplecodeinwhichwesetthesourceofaimageviewlionwhichissavedin
drawablefolder.
<ImageView
android
:i
d
="
@+id/simpleImageView"
android
:l
ayout_width="
fill_parent"
android
:l
ayout_height="wrap_content"
android
:s
rc
="@drawable/lion"/
><!--set
the
source
of
an
image
view
-->
InJava:
Wecanalsosetthesourceimageatruntimeprogrammaticallyinjavaclass.Forthatweuse
setImageResource()methodasshowninbelowexamplecode.
/*Add
in
Oncreate()
funtionaftersetContentView()*/
ImageView
simpleImageView
=(
ImageView )
findViewById
(R.
id
.s
impleImageView
);
simpleImageView
.s
etImageResource(R
.d
rawable.l
ion
);
//set the
source
in
javaclass
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
162
3.background:backgroundattributeisusedtosetthebackgroundofaImageView.Wecan
setacolororadrawableinthebackgroundofaImageView.
Belowistheexamplecodeinwhichwesettheblackcolorinthebackgroundandanimagein
thesrcattributeofimageview.
/*Add
in
Oncreate()
funtionafter
setContentView()*/
ImageView
simpleImageView
=(
ImageView )
findViewById
(R
.i
d
.s
impleImageView
);
simpleImageView
.s
etBackgroundColor(C
olor.B
LACK
);
//setblack
color
in
background
of
a
image
view
in
java
class
4.padding: paddingattributeisusedtosetthepaddingfromleft,right,toporbottomofthe
Imageview.
paddingRight:setthepaddingfromtherightsideoftheimageview.
paddingLeft:setthepaddingfromtheleftsideoftheimageview.
paddingTop:setthepaddingfromthetopsideoftheimageview.
paddingBottom:setthepaddingfromthebottomsideoftheimageview.
padding:setthepaddingfromtheallside’softheimageview.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
163
Belowistheexamplecodeofpaddingattributeinwhichwesetthe30dppaddingfromallthe
side’sofaimageview.
<ImageView
a
ndroid
:i
d
="
@+id/simpleImageView"
a
ndroid
:l
ayout_width="
fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:b
ackground
="
#000"
a
ndroid
:s
rc
="
@drawable/lion"
a
ndroid
:p
adding
="
30dp"/><!--set
3
0dp
paddingf
rom
all
the
sides
-->
5.scaleType:scaleTypeisanattributeusedtocontrolhowtheimageshouldbere-sizedor
movedtomatchthesizeofthisimageview.T
hevalueforscaletypeattributecanbefit_xy,
center_crop,fitStartetc.
Belowistheexamplecodeofscaletypeinwhichwesetthescaletypeofimageviewtofit_xy.
<ImageView
android
:i
d
="
@+id/simpleImageView"
android
:l
ayout_width="
fill_parent"
android
:l
ayout_height="wrap_content"
android
:s
rc
="@drawable/lion"
android
:s
caleType="
fitXY"/><!--
set
scale
type
fit
xy
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
164
Let’swetakeananotherexampleofscaletypetounderstandtheactualworkingofscale
typeinaimageview.
Inbelowexamplecodewesetthevalueforscaletype“fitStart” whichisusedtofittheimagein
thestartoftheimageviewasshownbelow:
<ImageView
a
ndroid
:i
d
="
@+id/simpleImageView"
a
ndroid
:l
ayout_width
="fill_parent"
a
ndroid
:l
ayout_height
="wrap_content"
a
ndroid
:s
rc
="
@drawable/lion"
a
ndroid
:s
caleType
="
fitStart"/><!--
set
scale
type
fit
start
of
image
view
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
165
ExampleofImageView:
BelowistheexampleofimageviewinwhichwedisplaytwoanimalimagesofLionandMonkey.
AndwheneveruserclickonanimageAnimalnameisdisplayedastoastonscreen.Belowisthe
finaloutputandcode:
Step1:CreateanewprojectandnameitImageViewExample.
Inthisstepwecreateanewprojectinandroidstudiobyfillingallthenecessarydetailsofthe
applikeappname,packagename,apiversionsetc.
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
a
nd
F
ill
the
formsa
nd
click"
Finish"
button.
Step2:D
ownloadtwoimageslionandmonkeyfromtheweb.Nowsavethoseimagesinthe
drawablefolderofyourproject.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
166
Step3:N
owopenres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthisstepweaddthecodefordisplayinganimageviewonthescreeninarelativelayout.Here
makesureyouhavealreadysavedtwoimagesnamelionandmonkeyinyourdrawablefolder.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools="
http://schemas.android.com/tools"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop ="
@dimen/activity_vertical_margin"
t
ools
:c
ontext="
.MainActivity">
<
ImageView
a
ndroid:i
d
="@+id/simpleImageViewLion"
a
ndroid:l
ayout_width ="
fill_parent"
a
ndroid:l
ayout_height ="200dp"
a
ndroid:s
caleType ="fitXY"
a
ndroid:s
rc
="@drawable/lion" /
>
<
ImageView
a
ndroid
:i
d
="
@+id/simpleImageViewMonkey"
a
ndroid
:l
ayout_width ="
fill_parent"
a
ndroid
:l
ayout_height ="200dp"
a
ndroid
:l
ayout_below ="
@+id/simpleImageViewLion"
a
ndroid
:l
ayout_marginTop ="
10dp"
a
ndroid
:s
caleType ="
fitXY"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
167
a
ndroid
:s
rc
="
@drawable/monkey"
/
>
</RelativeLayout>
Step4:N
owopenapp->java->package->MainActivity.javaandaddthefollowingcode:
Inthisstepweaddthecodetoinitiatetheimageview’sandthenperformclickeventonthem.
packageexample .abhiandriod .i
mageviewexample;
import
android .g
raphics .C
olor;
import
android .s
upport .v7
.app
.AppCompatActivity;
import
android .o
s.B
undle;
import
android .v
iew .M
enu;
import
android .v
iew .M
enuItem;
import
android .v
iew .V
iew;
import
android .w
idget .ImageView;
import
android .w
idget .Toast;
publicc
lassMainActivity extends A
ppCompatActivity {
@Override
protected
voidonCreate (B
undle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .a
ctivity_main );
ImageView
simpleImageViewLion= (
ImageView )
findViewById (R.
i
d.s
impleImageViewLion );//get the idoffirstimageview
ImageView
simpleImageViewMonkey= (I
mageView )
findViewById (R.
i
d.s
impleImageViewMonkey );
//get theid ofsecondimage
view
s
impleImageViewLion .s
etOnClickListener (n
ewV
iew .O
nClickListener ()
{
@Override
public void
onClick (View
view){
Toast
.makeText (g
etApplicationContext (),"
Lion",
Toast
.LENGTH_LONG ).
show ();//display thetext on image clickevent
}
});
s
impleImageViewMonkey .setOnClickListener (n
ewV
iew .O
nClickListener()
{
@Override
public void
onClick (View
view){
Toast
.makeText (g
etApplicationContext (),"
Monkey" ,
Toast
.LENGTH_LONG ).
show ();//display thetext on image clickevent
}
});
}
}
Output:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
168
NowstartAVDinEmulatorandruntheApp.YouwillseetheimagesofLionandMonkey
displayedonscreen.ClickonanyAnimalimageandhisnamewillappearonScreen.Weclicked
onLion.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
169
ImageButton
InAndroid,ImageButtonisusedtodisplayanormalbuttonwithacustomimageinabutton.In
simplewordswecansay,ImageButtonisabuttonwithanimagethatcanbepressedorclicked
bytheusers.Bydefaultitlookslikeanormalbuttonwiththestandardbuttonbackgroundthat
changesthecolorduringdifferentbuttonstates.
Animageonthesurfaceofabuttonisdefinedwithinaxml(i.e.layout)byusingsrcattributeor
withinjavaclassbyusingsetImageResource()method.Wecanalsosetanimageorcustom
drawableinthebackgroundoftheimagebutton.
ImportantNote:S tandardbuttonbackgroundimageisdisplayedinthebackgroundofbutton
wheneveryoucreateanimagebutton.Toremovethatimage,youcandefineyourown
backgroundimageinxmlbyusingbackgroundattributeorinjavaclassbyusing
setBackground()method.
BelowisthecodeandimagewhichshowshowcustomimagebuttonlooksinAndroid:
ImportantNote:I mageButtonhasallthepropertiesofanormalbuttonsoyoucaneasily
performanyeventlikeclickoranyothereventwhichyoucanperformonanormalbutton.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
170
ImageButtoncodeinXML:
<!--MakeSureTo
Add
ImageNamehomein
Drawable
Folder-->
<ImageButton
android
:i
d="
@+id/simpleImageButton"
android
:l
ayout_width ="
wrap_content"
android
:l
ayout_height ="wrap_content"
android
:s
rc="@drawable/home"/
>
AttributesofImageButton:
Nowlet’swediscusssomeimportantattributesthathelpsustoconfigureaimagebuttonin
yourxmlfile(layout).
1.id:idisanattributeusedtouniquelyidentifyaimagebutton.Belowistheexamplecodein
whichwesettheidofaimagebutton.
<ImageButton
android
:i
d
="
@+id/simpleImageButton"
android
:l
ayout_width
="
wrap_content"
android
:l
ayout_height
="wrap_content"
/>
2.src:s rcisanattributeusedtosetasourcefileofimageoryoucansayimageinyourimage
buttontomakeyourlayoutlookattractive.
Belowistheexamplecodeinwhichwesetthesourceofanimagebutton.Makesureyouhave
savedanimageindrawablefoldernamehomebeforeusingbelowcode.
<ImageButton
a
ndroid
:i
d="
@+id/simpleImageButton"
a
ndroid
:l
ayout_width="
wrap_content"
a
ndroid
:l
ayout_height="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
171
a
ndroid
:s
rc
="
@drawable/home"
/>
<
!--
src
(s
ource
)f
ilef
rom
drawable
folder
which
display
an
imagebutton
-->
SettingImageSourceInImageButtonUsingJavaclass:
Wecanalsosetthesourceimageatruntimeprogrammaticallyinjavaclass.Forthatweuse
setImageResource()functionasshowninbelowexamplecode.
/*Add
in
Oncreate()
funtion
aftersetContentView()*/
ImageButton
simpleImageButton=
(
ImageButton)f
indViewById(R
.i
d
.s
impleImageButton);
simpleImageButton
.s
etImageResource(R
.d
rawable
.home
);
/
/settheimage
programmatically
3.background:backgroundattributeisusedtosetthebackgroundofanimagebutton.We
cansetacolororadrawableinthebackgroundofaButton.
Belowistheexamplecodeinwhichwesettheblackcolorforthebackgroundandanhome
imageasthesourceoftheimagebutton.
<ImageButton
a
ndroid
:i
d="
@+id/simpleImageButton"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:s
rc="
@drawable/home"
a
ndroid
:b
ackground="
#000" /><!--
black
background
colorf
or
image
button
-->
SettingBackgroundInImageButtonUsingJavaclass:
Belowistheexamplecodeinwhichwesettheblackbackgroundcolorofaimagebutton
programmaticallymeansinjavaclass.
/*Add
in
Oncreate()
funtion
aftersetContentView()*/
ImageButton
simpleImageButton=
(
ImageButton
)
findViewById
(R
.i
d
.s
impleImageButton
);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
172
simpleImageButton
.s
etBackgroundColor
(C
olor
.B
LACK
);
/
/set
black
background
color
for
image
button
4.padding:paddingattributeisusedtosetthepaddingfromleft,right,toporbottomofthe
ImageButton.
paddingRight:s etthepaddingfromtherightsideoftheimagebutton.
paddingLeft:setthepaddingfromtheleftsideoftheimagebutton.
paddingTop:setthepaddingfromthetopsideoftheimagebutton.
paddingBottom:s etthepaddingfromthebottomsideoftheimagebutton.
padding:setthepaddingfromtheallside’softheimagebutton.
Belowistheexamplecodeofpaddingattributeinwhichwesetthe20dppaddingfromallthe
side’sofaimagebutton.
<ImageButton
a
ndroid
:i
d="
@+id/simpleImageButton"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:b
ackground="
#000"
a
ndroid
:s
rc="
@drawable/home"
a
ndroid
:p
adding="
30dp"/><!--s
et
3
0dp
paddingf
rom
all
the
sides
of
the
view
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
173
ExampleofImageButtonInAndroidStudio:
InthebelowexampleofImageButtonwedisplaytwocustomimagebuttonswithsourceand
background.Oneissimpleimagebuttonwithsimplebackgroundandotheroneisaround
cornerimagebuttonandwheneveryouclickonanbutton,thenameofthebuttonwillbe
displayedinatoast.Belowisthecodeandfinaloutput:
Step1:CreateanewprojectandnameitImageButtonExample
Inthisstepwecreateanewprojectinandroidstudiobyfillingallthenecessarydetailsofthe
applikeappname,packagename,apiversionsetc.
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
a
nd
F
ill
the
formsa
nd
click"
Finish"
button.
Step2:R
ightclickondrawable->New->Drawableresourcefileandcreatenewxmlfilename
custom_image-buttton.xmlandaddfollowingcode
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
174
InthisStepwecreatedrawablexmlinwhichweusedsolidandcornerproperties,solidisused
tosetthebackgroundcolorfortheimagebuttonandcornerisusedtosettheradiusforbutton
corners.
<?
xml
version ="
1.0"
encoding="
utf-8"?>
<shape
x
mlns:android ="
http://schemas.android.com/apk/res/android">
<solid
a
ndroid:color ="
#900"
/
>
<!-- background
color
for
imagebutton-->
<corners
a
ndroid:radius="
20dp"
/>
<!--round
corners
for
imagebutton-->
</shape>
Step3:O
penapp->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthisstep,weopenanxmlfileandaddthecodewhichdisplaytwocustomimagebuttonsby
usingsrc,background,gravityandotherattributesinRelativeLayout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:tools
="
http://schemas.android.com/tools"
a
ndroid:l
ayout_width ="
match_parent"
a
ndroid:l
ayout_height ="match_parent"
a
ndroid:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid:p
addingTop ="
@dimen/activity_vertical_margin"
t
ools
:context=".MainActivity">
<!--Makesure
to save
two imageshome andyoutubein
drawable folder-->
<
ImageButton
a
ndroid:i
d ="
@+id/simpleImageButtonHome"
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:l
ayout_centerHorizontal ="true"
a
ndroid:b
ackground ="@drawable/custom_image_button"
a
ndroid:p
adding ="20dp"
a
ndroid:s
rc ="
@drawable/home" /
>
<
ImageButton
a
ndroid:i
d ="
@+id/simpleImageButtonYouTube"
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:l
ayout_below ="
@+id/simpleImageButtonHome"
a
ndroid:l
ayout_centerHorizontal ="true"
a
ndroid:l
ayout_marginTop ="
20dp"
a
ndroid:b
ackground ="#005"
a
ndroid:p
adding ="20dp"
a
ndroid:s
rc ="
@drawable/youtube" />
</RelativeLayout>
Step4:O
penapp->package->MainActivity.java
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
175
Inthisstep,weaddthecodetoinitiatetheimagebutton’sandthenperformclickeventon
themanddisplaythetextforselecteditemusingatoast.
package example .abhiandriod .imagebuttonexample;
import
android .a
pp .A
ctivity;
import
android .g
raphics .C
olor;
import
android .s
upport .v7
.app.A
ppCompatActivity;
import
android .o
s.Bundle;
import
android .v
iew .Menu;
import
android .v
iew .MenuItem;
import
android .v
iew .View;
import
android .w
idget .ImageButton;
import
android .w
idget .Toast;
public c
lassMainActivity extends A
ctivity{
@Override
protected
void onCreate (Bundle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .a
ctivity_main );
//
initiate view's
ImageButton
simpleImageButtonHome=
(
ImageButton )findViewById (R.
id
.simpleImageButtonHome );
ImageButton
simpleImageButtonYouTube=
(
ImageButton )findViewById (R.
id
.simpleImageButtonYouTube );
//
perform click event onbutton's
s
impleImageButtonHome .setOnClickListener (n
ew
V
iew .O
nClickListener
()
{
@Override
public void
onClick (View
view
){
Toast
.makeText (g
etApplicationContext (),"Home
Button" ,Toast.LENGTH_LONG ).show ();//display the toastonhome
button
click
}
});
s
impleImageButtonYouTube .s
etOnClickListener (n
ewV
iew.O
nClickListener(){
@Override
public void
onClick (View
view
){
Toast
.makeText (g
etApplicationContext (),"YouTube
Button" ,Toast.LENGTH_LONG ).show ();//display the toastonyou
tube
button
click
}
});
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
176
Output:
NowstarttheAVDinEmulatorandruntheApp.YouwillseetwoImageButtonoutofwhichtop
oneisroundcorner.Clickonanyimageanditsnamewillbedisplayedonscreen.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
177
CheckBox
InAndroid,CheckBoxisatypeoftwostatebuttoneitheruncheckedorcheckedinAndroid.Or
youcansayitisatypeofon/offswitchthatcanbetoggledbytheusers.Youshoulduse
checkboxwhenpresentingagroupofselectableoptionstousersthatarenotmutually
exclusive.CompoundButtonistheparentclassofCheckBoxclass.
Inandroidthereisalotofusageofcheckbox.Forexample,totakesurveyinAndroidappwe
canlistfewoptionsandallowusertochooseusingCheckBox.Theuserwillsimplychecked
thesecheckboxesratherthantypetheirownoptioninEditText.Anotherverycommonuseof
CheckBoxisasremembermeoptioninLoginform.
CheckBoxcodeinXML:
<CheckBox
android
:i
d="
@+id/simpleCheckBox"
android
:l
ayout_width ="
wrap_content"
android
:l
ayout_height ="wrap_content"
android
:t
ext ="
Simple
CheckBox"/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
178
ImportantNote:Youcancheckthecurrentstateofacheckboxprogrammaticallybyusing
isChecked()method.ThismethodreturnsaBooleanvalueeithertrueorfalse,ifacheckboxis
checkedthenitreturnstrueotherwiseitreturnsfalse.Belowisanexamplecodeinwhichwe
checkedthecurrentstateofacheckbox.
//initiatea
check
box
CheckBox
simpleCheckBox=
(C
heckBox
)
findViewById(R
.i
d
.s
impleCheckBox
);
//checkcurrent
state
ofa
check
box
(true
or
false)
Boolean
checkBoxState=
simpleCheckBox.i
sChecked
();
AttributesofCheckBox:
Nowlet’s wediscussimportantattributesthathelpsustoconfigureacheckboxinXMLfile
(layout).
1.id:idisanattributeusedtouniquelyidentifyacheckbox.Belowwesettheidofaimage
button.
<CheckBox
android
:i
d="
@+id/simpleCheckBox"
android
:l
ayout_width ="
wrap_content"
android
:l
ayout_height ="wrap_content"
android
:t
ext ="
Simple
CheckBox"/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
179
2.checked:checkedisanattributeofcheckboxusedtosetthecurrentstateofacheckbox.
Thevalueshouldbetrueorfalsewheretrueshowsthecheckedstateandfalseshowsunchecked
stateofacheckbox.Thedefaultvalueofcheckedattributeisfalse.Wecanalsosetthecurrent
stateprogrammatically.
Belowisanexamplecodeinwhichwesettruevalueforcheckedattributethatsetsthecurrent
statetochecked.
<CheckBox
a
ndroid
:i
d
="
@+id/simpleCheckBox"
a
ndroid
:l
ayout_width="
wrap_content"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:t
ext="
Simple
CheckBox"
a
ndroid
:c
hecked="
true"
/><
!--
set
the
current
state
of
the
check
box
-->
SettingCurrentStateOfCheckBoxInJavaClass:
BelowwesetthecurrentstateofCheckBoxinjavaclass.
/*Add
inOncreate()
funtion aftersetContentView()*/
//
initiatea
check
box
CheckBox
simpleCheckBox=(
CheckBox)
findViewById
(R
.i
d
.s
impleCheckBox
);
//
setthe
current
stateofa
checkbox
simpleCheckBox.s
etChecked(t
rue);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
180
3.gravity:Thegravityattributeisanoptionalattributewhichisusedtocontrolthealignment
ofthetextinCheckBoxlikeleft,right,center,top,bottom,center_vertical,center_horizontal
etc.
Belowwesettherightandcenter_verticalgravityforthetextofacheckbox.
<CheckBox
a
ndroid
:i
d
="
@+id/simpleCheckBox"
a
ndroid
:l
ayout_width="
fill_parent"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:t
ext="
Simple
CheckBox"
a
ndroid
:c
hecked="
true"
a
ndroid
:g
ravity="
right|center_vertical"/>
<
!--
gravity
of
the
check
box
-->
4.text:textattributeisusedtosetthetextinacheckbox.Wecansetthetextinxmlaswellas
inthejavaclass.
Belowistheexamplecodewithexplanationincludedinwhichwesetthetext“TextAttributeOf
CheckBox”foracheckbox.
<CheckBox
a
ndroid
:i
d
="
@+id/simpleCheckBox"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:c
hecked="
true"
a
ndroid
:t
ext="
Text
Attribute Of
Check
Box"
/>
<
!--
displayed
text
of
the
check
box
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
181
SettingtextinCheckBoxInJavaclass:
Belowistheexamplecodeinwhichwesetthetextofacheckboxprogrammaticallymeansin
javaclass.
/*Add
in
Oncreate()
funtion after
setContentView()*/
//
initiate
check
box
CheckBox
simpleCheckBox=(
CheckBox
)
findViewById(R
.i
d
.s
impleCheckBox
);
//
displayed
text
of
thecheckbox
simpleCheckBox
.s
etText
("
Text Attribute
Of
Check
Box" );
5.textColor:t extColorattributeisusedtosetthetextcolorofacheckbox.Colorvalueisin
formof“#argb”,“#rgb”,“#rrggbb”,or“#aarrggbb”.
Belowwesettheredcolorforthedisplayedtextofacheckbox.
<CheckBox
a
ndroid
:i
d
="
@+id/simpleCheckBox"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext="
Text is
Red Color"
a
ndroid
:t
extColor ="
#f00"
a
ndroid
:c
hecked="
true" /><
!--
red
colorf
or
the
text
of
check
box
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
182
SettingtextColorinCheckBoxInJavaclass:
Belowwesetthetextcolorofacheckboxprogrammatically.
/*Add
in
Oncreate()funtion aftersetContentView()*/
//initiate
thecheckbox
CheckBox
simpleCheckBox= (
CheckBox)
findViewById
(R
.i
d
.s
impleCheckBox
);
//red
color
fordisplayedtext
simpleCheckBox
.s
etTextColor (Color
.R
ED);
6.textSize:t extSizeattributeisusedtosetthesizeoftextofacheckbox.Wecansetthetext
sizeinsp(scaleindependentpixel)ordp(densitypixel).
Belowistheexamplecodeinwhichwesetthe20spsizeforthetextofacheckbox.
<CheckBox
a
ndroid
:i
d
="
@+id/simpleCheckBox"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext="
Text size AttributeOfCheckBox"
a
ndroid
:t
extColor ="
#00f"
a
ndroid
:c
hecked="
false"
a
ndroid
:t
extSize="20sp" /><!--set
T
extSize
oftexti
n
C
heckBox
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
183
SettingTextSizeinCheckBoxInJavaclass:
Belowwesetthetextsizeofacheckboxinjavaclass.
/*Add
in
Oncreate()
funtionafter
setContentView()*/
CheckBox
simpleCheckBox=
(
CheckBox
)
findViewById
(R
.i
d
.s
impleCheckBox
);
//set
20sp
displayed
text
size
simpleCheckBox
.s
etTextSize
(2
0);
7.textStyle:textStyleattributeisusedtosetthetextstyleofthetextofacheckbox.The
possibletextstylesarebold,italicandnormal. Ifweneedtousetwoormorestylesforatext
viewthen“|”operatorisusedforthat.
Belowwesettheboldanditalictextstylesfortextofacheckbox.
<CheckBox
a
ndroid
:i
d
="
@+id/simpleCheckBox"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext="
Text Style AttributeOf
Check
Box"
a
ndroid
:t
extColor ="
#44f"
a
ndroid
:t
extSize="20sp"
a
ndroid
:c
hecked="
false"
a
ndroid
:t
extStyle ="
bold|italic" />
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
184
8.background:backgroundattributeisusedtosetthebackgroundofacheckbox.Wecanset
acolororadrawableinthebackgroundofacheckbox.
Belowwesettheblackcolorforthebackground,whitecolorforthedisplayedtextofacheck
box.
<CheckBox
a
ndroid
:i
d
="
@+id/simpleCheckBox"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext="
Text size AttributeOfCheck
Box"
a
ndroid
:t
extColor ="
#fff"
a
ndroid
:t
extSize="20sp"
a
ndroid
:t
extStyle ="
bold|italic"
a
ndroid
:c
hecked="
true"
a
ndroid
:b
ackground ="
#000" /
><!--
black backgroundf
or
the
background
of
check
box
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
185
SettingBackgroundinCheckBoxInJavaclass:
Belowistheexamplecodeinwhichwesetthebackgroundcolorofacheckbox
programmaticallymeansinjavaclass.
/*Add
inOncreate()
funtion after
setContentView()*/
CheckBox
simpleCheckBox=(
CheckBox)
findViewById(R
.i
d
.s
impleCheckBox
);
//
setbackground
inCheckBox
simpleCheckBox.s
etBackgroundColor (C
olor.B
LACK
);
9.padding:p
addingattributeisusedtosetthepaddingfromleft,right,toporbottom.
paddingRight: setthepaddingfromtherightsideofthecheckbox.
paddingLeft: setthepaddingfromtheleftsideofthecheckbox.
paddingTop: setthepaddingfromthetopsideofthecheckbox.
paddingBottom:setthepaddingfromthebottomsideofthecheckbox.
Padding:setthepaddingfromtheallside’softhecheckbox.
Belowistheexamplecodeofpaddingwherewesetthe30dppaddingfromalltheside’softhe
checkbox.
<CheckBox
a
ndroid
:i
d
="
@+id/simpleCheckBox"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:t
ext="
Padding Attribute OfCheck
Box"
a
ndroid
:t
extColor ="
#44f"
a
ndroid
:t
extSize="20sp"
a
ndroid
:t
extStyle ="
bold|italic"
a
ndroid
:c
hecked="
false"
a
ndroid
:p
adding="
30dp"/> <
!--
30dp
paddingfrom
all
side
's-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
186
ExampleofCheckBoxInAndroidStudio:
BelowistheexampleofCheckBoxinAndroid,inwhichwedisplayfivecheckboxesusing
backgroundandotherattributeswediscussesearlierinthispost.Everycheckboxrepresentsa
differentsubjectnameandwheneveryouclickonacheckboxthentextofthatcheckedcheck
boxisdisplayedinatoast.Belowisthefinaloutput,codeandstepbystepexplanationofthe
example:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
187
Step1:C
reateanewprojectandnameitCheckBoxExample
Inthisstepwecreateanewprojectinandroidstudiobyfillingallthenecessarydetailsofthe
applikeappname,packagename,apiversionsetc.
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
a
nd
F
ill
the
formsa
nd
click"
Finish"
button.
Step2:NowOpenres->layout->activity_main.xml(or)main.xmlandaddthefollowingcode:
InthisstepweopenanxmlfileandaddthecodefordisplayingfiveoneTextViewandcheck
boxes.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools="
http://schemas.android.com/tools"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop ="
@dimen/activity_vertical_margin"
t
ools
:c
ontext=".MainActivity">
<
TextView
a
ndroid:l
ayout_width ="wrap_content"
a
ndroid:l
ayout_height ="
wrap_content"
a
ndroid:t
ext ="
Select Your Programming language:
"
a
ndroid:t
extColor ="#f00"
a
ndroid:t
extSize ="
20sp"
a
ndroid:t
extStyle ="bold" /
>
<
LinearLayout
a
ndroid:i
d="
@+id/linearLayout"
a
ndroid:l
ayout_width ="fill_parent"
a
ndroid:l
ayout_height ="
wrap_content"
a
ndroid:l
ayout_marginTop ="
30dp"
a
ndroid:b
ackground ="#e0e0e0"
a
ndroid:o
rientation ="
vertical">
<
CheckBox
android:id
="
@+id/androidCheckBox"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_centerHorizontal ="true"
android:checked ="
false"
android:padding ="
20dp"
android:text="
@string/android"
android:textColor ="
#44f"
android:textSize ="20sp"
android:textStyle ="
bold|italic" />
<
CheckBox
android:id
="
@+id/javaCheckBox"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
188
a
ndroid
:l
ayout_centerHorizontal ="
true"
a
ndroid
:c
hecked="
false"
a
ndroid
:p
adding="
20dp"
a
ndroid
:t
ext
="@string/java"
a
ndroid
:t
extColor ="
#f44"
a
ndroid
:t
extSize="20sp"
a
ndroid
:t
extStyle ="
bold|italic"
/
>
<
CheckBox
a
ndroid
:i
d
="
@+id/phpCheckBox"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_centerHorizontal ="
true"
a
ndroid
:c
hecked="
false"
a
ndroid
:p
adding="
20dp"
a
ndroid
:t
ext="
@string/php"
a
ndroid
:t
extColor ="
#444"
a
ndroid
:t
extSize="20sp"
a
ndroid
:t
extStyle ="
bold|italic"/
>
<
CheckBox
a
ndroid
:i
d
="
@+id/pythonCheckBox"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_centerHorizontal ="
true"
a
ndroid
:c
hecked="
false"
a
ndroid
:p
adding="
20dp"
a
ndroid
:t
ext="
@string/python"
a
ndroid
:t
extColor ="
#888"
a
ndroid
:t
extSize="20sp"
a
ndroid
:t
extStyle ="
bold|italic"/
>
<
CheckBox
a
ndroid
:id
="
@+id/unityCheckBox"
a
ndroid
:layout_width ="
wrap_content"
a
ndroid
:layout_height ="wrap_content"
a
ndroid
:layout_centerHorizontal ="true"
a
ndroid
:checked="
false"
a
ndroid
:padding="
20dp"
a
ndroid
:text="
@string/unity"
a
ndroid
:textColor ="
#101010"
a
ndroid
:textSize="20sp"
a
ndroid
:textStyle ="
bold|italic"/>
</LinearLayout>
</RelativeLayout>
Step3:N
owOpen app->java->package->MainActivity.java
Inthisstepweaddthecodetoinitiatethecheckboxeswecreated.Andthenweperformclick
eventonbuttonanddisplaythetextforselectedcheckboxesusingatoast.
package
example
.abhiandriod .c
heckboxexample;
import
android.g
raphics.Color;
import
android.s
upport.v
7.a
pp.A
ppCompatActivity;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
189
import
android .o
s.Bundle;
import
android .v
iew .Menu;
import
android .v
iew .MenuItem;
import
android .v
iew .View;
import
android .w
idget .Button;
import
android .w
idget .CheckBox;
import
android .w
idget .Toast;
publicc
lassMainActivity extends A
ppCompatActivity i
mplements View.OnClickListener
{
CheckBox
android ,java ,python , php, unity3D;
@Override
protected
void onCreate (B
undle savedInstanceState )
{
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .activity_main );
//
initiate views
a
ndroid= (C
heckBox )findViewById (R
.i
d
.androidCheckBox );
a
ndroid .setOnClickListener (this );
j
ava= (
CheckBox )findViewById (R
.i
d.javaCheckBox );
j
ava.setOnClickListener (this );
p
ython= (CheckBox )findViewById (R
.i
d.p
ythonCheckBox );
p
ython .s
etOnClickListener (t
his );
p
hp=(C
heckBox ) findViewById (R.
id.p
hpCheckBox );
p
hp
.s
etOnClickListener (this );
u
nity3D= (C
heckBox )findViewById (R
.i
d
.unityCheckBox );
u
nity3D .setOnClickListener (this );
}
@Override
public
v
oid onClick (View view ){
switch
(
view .g
etId ())
{
case R.
i
d.androidCheckBox:
if
(
android .i
sChecked ())
Toast .makeText (getApplicationContext (),"
Android" ,
Toast
.LENGTH_LONG ).show ();
break;
case R.
i
d.javaCheckBox:
if
(
java .isChecked ())
Toast .makeText (getApplicationContext (),"
Java" ,
Toast
.LENGTH_LONG ).show ();
break;
case R.
i
d.phpCheckBox:
if
(
php.isChecked ())
Toast .makeText (getApplicationContext (),"
PHP" ,
Toast
.LENGTH_LONG ).show ();
break;
case R.
i
d.pythonCheckBox:
if
(
python .isChecked ())
Toast .makeText (getApplicationContext (),"
Python" ,
Toast
.LENGTH_LONG ).show ();
break;
case R.
i
d.unityCheckBox:
if
(
unity3D .i
sChecked ())
Toast .makeText (getApplicationContext (),"
Unity 3D",
Toast
.LENGTH_LONG ).show ();
break;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
190
}
}
}
Step5:Openres->values->strings.xml
Inthisstepweshowstringfilewhichisusedtostorestringdataofanapp.
<resources>
<string
n
ame
="app_name">CheckBoxExample</string>
<string
n
ame
="hello_world" >H
elloworld!</string>
<string
n
ame
="action_settings" >S
ettings</string>
<string
n
ame
="android">Android
</string>
<string
n
ame
="java"
>Java</string>
<string
n
ame
="php"
>P
HP</string>
<string
n
ame
="python">
Python
</string>
<string
n
ame
="unity"
>Unity3D
</string>
</resources>
Output:
NowstarttheAVDinEmulatorandruntheApp.Youwillsee5checkboxoptionaskingyouto
chooseyourprogramminglanguage.SelectandthetextofthatparticularCheckBoxwillappear
onScreen.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
191
Switch
InAndroid,Switchisatwo-statetoggleswitchwidgetthatcanselectbetweentwooptions.Itis
usedtodisplaycheckedanduncheckedstateofabuttonprovidingslidercontroltouser.Switch
isasubclassofCompoundButton.Itisbasicallyanoff/onbuttonwhichindicatethecurrent
stateofSwitch.Itiscommonlyusedinselectingon/offinSound,Bluetooth,WiFietc.
AscomparedtoToggleButtonSwitchprovidesuserslidercontrol.Theusercansimplytapona
switchtochangeitscurrentstate.
Switchallowtheuserstochangethesettingbetweentwostatesliketurnon/off wifi,Bluetooth
etcfromyourphone’ssettingmenu.ItwasintroducedafterAndroid4.0version(APIlevel14).
ImportantNote:A
ndroidSwitchandToggleButtonbotharethesubclassesof
CompoundButtonclass.
SwitchcodeinXML:
<Switch
android
:id
="
@+id/simpleSwitch"
android
:layout_width
="
wrap_content"
android
:layout_height
="wrap_content"
/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
192
ImportantNote:W
ecancheckthecurrentstateofaSwitchprogrammaticallybyusing
isChecked()method.ThismethodreturnsaBooleanvaluemeanstrueorfalse.IfaSwitchis
checkedthenitreturnstrueotherwiseitreturnsfalse.
BelowisanexamplecodeinwhichwecheckedthecurrentstateofaSwitch.
//
initiate a
Switch
Switch
simpleSwitch= (
S
witch)
findViewById
(R
.i
d.s
impleSwitch
);
//
check current
stateof
a
Switch
(true
orfalse).
Boolean
switchState=
simpleSwitch.i
sChecked();
AttributesofSwitch:
Nowlet’s wediscussimportantSwitchattributesthathelpsustoconfigureaSwitchinXML
file(layout).
1.id:idisanattributeusedtouniquelyidentifyaSwitch.
<Switch
android
:id
="
@+id/simpleSwitch"
android
:layout_width
="
wrap_content"
android
:layout_height
="wrap_content"
/>
2.checked:c heckedattributeofSwitchisusedtosetthecurrentstateofaSwitch.Thevalue
canbeeithertrueorfalsewheretrueshowsthecheckedstateandfalseshowsuncheckedstate
ofaSwitch.Thedefaultvalueofcheckedattributeisfalse.Wecanalsosetthecurrentstate
programmatically.
Belowweset“true”valueforcheckedattributethatsetsthecurrentstatetochecked.
<Switch
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
193
android
:i
d
="
@+id/simpleSwitch"
android
:l
ayout_width
="
wrap_content"
android
:l
ayout_height
="wrap_content"
android
:c
hecked
="
true"
/><
!--
s
et
thecurrent
state
of
theS
witch
-->
SettingCheckAttributeInSwitchUsingJavaClass:
BelowwesetthecurrentstateofSwitchinjavaclass.
/*Add
in
Oncreate() funtion after
setContentView()*/
//
initiateaSwitch
Switch
simpleSwitch= (
S
witch )
findViewById
(R
.i
d
.s
impleSwitch
);
//set
thecurrentstateof
aSwitch
simpleSwitch.s
etChecked (t
rue
);
3.text:textattributeisusedtosetthetextinaSwitch.Wecansetthetextinxmlaswellasin
thejavaclass.
Belowwesetthetext“Sound”fortheSwitch.
<Switch
android
:id
="
@+id/simpleSwitch"
android
:layout_width="wrap_content"
android
:layout_height="wrap_content"
android
:layout_centerHorizontal ="
true"
android
:text="
Sound"
/
><
!--
displayedtext
ofs
witch
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
194
SettingTextInSwitchUsingJavaclass:
InthebelowcodewesettextofSwitchviajavaclass.
/*Add
in
Oncreate()funtion after
setContentView()*/
//
initiate
Switch
Switch
simpleSwitch=(S
witch)
findViewById
(R
.i
d
.s
impleSwitch
);
//displayed
textof
the Switch
simpleSwitch
.setText
("
switch" );
4.gravity:Thegravityattributeisanoptionalattributewhichisusedtocontrolthealignment
ofthetextinSwitch.Wecansettextleft,right,center,top,bottom,center_vertical,
center_horizontaletcinSwitch.
InthebelowcodewesettheleftgravityforthetextinSwitch.
<Switch
a
ndroid
:i
d
="
@+id/simpleSwitch"
a
ndroid
:l
ayout_width="fill_parent"
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:t
ext="
Sound"
a
ndroid
:c
hecked="
true"
a
ndroid
:g
ravity="
left"/><!--
gravity
of
theS
witch
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
195
5.textOnAndtestOff:t extOnattributeisusedtosetthetextwhenSwitchisinchecked
state(i.e.onstate).WecansetthetextOninXMLaswellasinthejavaclass.
InthebelowexamplewesetthetextOnas“Yes”andtextOffas“No”foraSwitch
<Switch
a
ndroid
:i
d
="
@+id/simpleSwitch"
a
ndroid
:l
ayout_width="wrap_content"
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:c
hecked="
true"
a
ndroid
:t
ext="
Notification"
a
ndroid
:t
extOff="
No"
a
ndroid
:t
extOn="
Yes"
/><!--
text
to
bedisplayed
whenever
current
statei
s
c
hecked
-->
SettingtextOnAndtestOffofSwitchInJavaclass:
BelowwesetthetextOnandtextOffofaSwitchinjavaclass
/*Add
in
Oncreate()funtion aftersetContentView()*/
Switch
simpleSwitch=(
S
witch )
findViewById(R
.i
d
.s
impleSwitch
);/
/
initiate
Switch
simpleSwitch
.setTextOn
("On"
);/
/
displayedtextof
the
Switchwhenever
it
isin
checked
or
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
196
on
state
simpleSwitch.s
etTextOff
("
Off"
);
/
/
displayed
text
of
the
Switch
whenever
it
is
in
unchecked
i.e.
offstate
6.textColor:t extColorattributeisusedtosetthetextcolorofaSwitch.Colorvalueisinthe
formof“#argb”,“#rgb”,“#rrggbb”,or“#aarrggbb”.
Belowistheexamplecodewithexplanationincludedinwhichwesettheredcolorforthe
displayedtextofaSwitch.
<Switch
a
ndroid
:i
d
="
@+id/simpleSwitch"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:c
hecked="
true"
a
ndroid
:t
ext="
switch"
a
ndroid
:l
ayout_centerHorizontal ="
true"
a
ndroid
:t
extOn="
On"
a
ndroid
:t
extOff="
Off"
a
ndroid
:g
ravity="
center"
a
ndroid
:t
extColor ="
#008F36" /><!-- G
reen
colorf
or
displayed
text
-->
SettingtextColorOfSwitchtextInJavaclass:
BelowistheexamplecodeinwhichwesetthetextcolorofaSwitchprogrammatically.
/*Add
inOncreate()
funtion aftersetContentView()*/
S
witch
simpleSwitch=(
Switch)
findViewById(R
.i
d
.s
impleSwitch
);
//
initiate
Switch
simpleSwitch.s
etTextColor(C
olor.GREEN
);
/
/redcolor
for
displayed
text
of
Switch
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
197
7.textSize:t extSizeattributeisusedtosetthesizeofthetextofaSwitch.Wecansetthetext
sizeinsp(scaleindependentpixel)ordp(densitypixel).
Belowistheexamplecodeinwhichwesetthe25spsizeforthetextofaSwitch.
<Switch
a
ndroid
:i
d
="
@+id/simpleSwitch"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:c
hecked="
true"
a
ndroid
:t
ext="
switch"
a
ndroid
:l
ayout_centerHorizontal ="
true"
a
ndroid
:t
extOn="
On"
a
ndroid
:t
extOff="
Off"
a
ndroid
:t
extColor ="#f00"
a
ndroid
:g
ravity="
center"
a
ndroid
:t
extSize ="
25sp" /><
!--
25sp
displayed
text
size
-->
SettingtextSizeOfSwitchTextInJavaclass:
BelowistheexamplecodeinwhichwesetthetextsizeofaSwitchprogrammatically.
Switch
simpleSwitch=(
Switch
)findViewById
(R
.i
d
.s
impleSwitch
);/
/initiate
Switch
simpleSwitch
.setTextSize(2
5
);
/
/set
25sp
displayedtext
sizeofSwitch
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
198
9.textStyle:t extStyleattributeisusedtosetthetextstyleofthetextofaSwitch.The
possibletextstylesarebold,italicandnormal. Ifweneedtousetwoormorestylesforatext
viewthenuse“|”operator.
BelowwesettheboldanditalictextstylesfortextofaSwitch.
<Switch
a
ndroid
:i
d
="
@+id/simpleSwitch"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:c
hecked="
false"
a
ndroid
:t
ext="
switch"
a
ndroid
:l
ayout_centerHorizontal ="
true"
a
ndroid
:t
extOn="
On"
a
ndroid
:t
extOff="
Off"
a
ndroid
:t
extColor ="#f00"
a
ndroid
:g
ravity="
center"
a
ndroid
:t
extSize ="
25sp"
a
ndroid
:t
extStyle ="bold|italic" /><!--
bolda
nd
italic
text
stylef
or
displayed
text
-->
10.background:b ackgroundattributeisusedtosetthebackgroundofaSwitch.Wecanseta
colororadrawableinthebackgroundofaSwitch.
BelowwesettheblackcolorforthebackgroundandredcolorforthedisplayedtextofaSwitch.
<Switch
a
ndroid
:i
d
="
@+id/simpleSwitch"
a
ndroid
:l
ayout_width
="wrap_content"
a
ndroid
:l
ayout_height
="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
199
a
ndroid
:c
hecked="
true"
a
ndroid
:t
ext
="switch"
a
ndroid
:l
ayout_centerHorizontal ="true"
a
ndroid
:t
extOn="
On"
a
ndroid
:t
extOff="
Off"
a
ndroid
:t
extColor ="#f00"
a
ndroid
:p
adding="
20dp"
a
ndroid
:g
ravity="
center"
a
ndroid
:t
extSize ="
25sp"
a
ndroid
:b
ackground ="#000"/><!--
blackbackground
color
-->
SettingBackgroundInJavaclass:
BelowwesetthebackgroundcolorofaSwitchprogrammatically.
Switch
simpleSwitch=(
S
witch
)
findViewById(R
.i
d
.s
impleSwitch
);
simpleSwitch
.setBackgroundColor
(Color
.B
LACK
);
11.padding:p
addingattributeisusedtosetthepaddingfromleft,right,toporbottomin
Switch.
paddingRight:setthepaddingfromtherightsideoftheSwitch.
paddingLeft:s etthepaddingfromtheleftsideoftheSwitch.
paddingTop:s etthepaddingfromthetopsideoftheSwitch.
paddingBottom:setthepaddingfromthebottomsideoftheSwitch.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
200
Padding:s etthepaddingfromtheallside’softheSwitch.
Belowwesetthe20dppaddingfromalltheside’softheSwitch.
<Switch
a
ndroid
:i
d
="
@+id/simpleSwitch"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:c
hecked="
true"
a
ndroid
:t
ext="
switch"
a
ndroid
:l
ayout_centerHorizontal ="
true"
a
ndroid
:t
extOn="
On"
a
ndroid
:t
extOff="
Off"
a
ndroid
:t
extColor ="#f00"
a
ndroid
:g
ravity="
center"
a
ndroid
:t
extSize ="
25sp"
a
ndroid
:p
adding="
40dp" /><!--2
0dp
paddingf
rom
all
the
side
's-->
12.drawableBottom,drawableTop,drawableRightAnddrawableLeft:These
attributedrawthedrawablebelow,top,rightandleftofthetextofSwitch.
BelowwesettheicontothebelowofthetextofaSwitch.Youcantryotherthreebyyourself.
Beforeyoutrythismakesureyouhaveiconimageindrawablefolder
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
201
<Switch
a
ndroid
:i
d
="
@+id/simpleSwitch"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:c
hecked="
true"
a
ndroid
:t
ext="
switch"
a
ndroid
:l
ayout_centerHorizontal ="
true"
a
ndroid
:t
extOn="
On"
a
ndroid
:t
extOff="
Off"
a
ndroid
:t
extColor ="#f00"
a
ndroid
:g
ravity="
center"
a
ndroid
:t
extSize ="
25sp"
a
ndroid
:d
rawableBottom ="
@drawable/ic_launcher"
/><!--
drawable
icon
to
be
displayedi
n
the
bottom
of
text
-->
ExampleofSwitchInAndroidStudio:
BelowistheexampleofSwitchinAndroidStudio.Inthisexample,wedisplaytwoSwitchesand
one“submit”buttonusingbackground&otherattributesasdiscussedearlierinthispost.
WheneveryouclickonsubmitbuttonthecurrentstateforboththeSwitch’sisdisplayedina
Toast.Belowisthefinaloutput,codeandexampleexplainedstepbystep:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
202
Step1:C
reateanewprojectandnameitSwitchExample
Inthisstepwecreateanewprojectinandroidstudiobyfillingallthenecessarydetailsofthe
applikeappname,packagename,apiversionsetc.
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
F
ill
the
formsa
nd
click"
Finish"
button
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepweopenanxmlfileandaddthecodefordisplayingtwoSwitchandonenormal
button.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools
="
http://schemas.android.com/tools"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:o
rientation="vertical"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop="
@dimen/activity_vertical_margin"
t
ools
:c
ontext
="
.MainActivity">
<
Switch
a
ndroid
:i
d
="@+id/simpleSwitch1"
a
ndroid
:l
ayout_width ="
wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
203
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:l
ayout_gravity ="center"
a
ndroid
:c
hecked
="false"
a
ndroid
:t
ext
="
switch 1"
a
ndroid
:t
extOff
="Off"
a
ndroid
:t
extOn
="
On"/
>
<
Switch
a
ndroid
:i
d
="
@+id/simpleSwitch2"
a
ndroid
:l
ayout_width ="wrap_content"
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:l
ayout_gravity ="center"
a
ndroid
:l
ayout_marginTop ="
20dp"
a
ndroid
:c
hecked="true"
a
ndroid
:t
ext="
switch 2"
a
ndroid
:t
extOff="Off"
a
ndroid
:t
extOn="
On"/
>
<
Button
a
ndroid
:id
="
@+id/submitButton"
a
ndroid
:layout_width ="
wrap_content"
a
ndroid
:layout_height ="wrap_content"
a
ndroid
:layout_gravity ="center"
a
ndroid
:layout_marginTop ="50dp"
a
ndroid
:background ="#009284"
a
ndroid
:padding="
10dp"
a
ndroid
:text="
Submit"
a
ndroid
:textColor ="
#fff"
a
ndroid
:textStyle ="
bold" />
</LinearLayout>
Step3:O
pen app->java->package->MainActivity.java
InthisstepweopenMainActivitywhereweaddthecodetoinitiatethetwoSwitch’sandone
normalbutton.Andthenweperformclickeventonbuttonanddisplaythetextofcurrentstate
ofSwitchbyusingatoast.
package
example.abhiandriod .s
witchexample;
import
android .s
upport .v
7.app
.A
ppCompatActivity;
import
android .o
s.B
undle;
import
android .v
iew .V
iew;
import
android .w
idget .B
utton;
import
android .w
idget .S
witch;
import
android .w
idget .T
oast;
public
c
lassM
ainActivity extends A
ppCompatActivity
{
Switch
simpleSwitch1 ,simpleSwitch2;
Button
submit;
@Override
protected
voidonCreate (B
undle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout.a
ctivity_main );
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
204
/
/ initiate view's
s
impleSwitch1= (
Switch)findViewById (R
.i
d.s
impleSwitch1 );
s
impleSwitch2= (
Switch)findViewById (R
.i
d.s
impleSwitch2 );
s
ubmit = (Button) findViewById(R.id.submitButton);
s
ubmit .s
etOnClickListener (n
ewV
iew
.O
nClickListener (){
@Override
public v
oid
onClick (View
view
){
String
statusSwitch1 ,
statusSwitch2 ;
if
(
simpleSwitch1 .i
sChecked ())
s
tatusSwitch1= simpleSwitch1 .g
etTextOn(). toString();
else
s
tatusSwitch1= simpleSwitch1 .g
etTextOff ().toString ();
if
(
simpleSwitch2 .i
sChecked ())
s
tatusSwitch2= simpleSwitch2 .g
etTextOn(). toString();
else
s
tatusSwitch2= simpleSwitch2 .g
etTextOff ().toString ();
Toast
.makeText (g
etApplicationContext (),
"
Switch1 :"+
statusSwitch1+
"\n"
+
"Switch2 :"
+
statusSwitch2 ,T
oast .L
ENGTH_LONG ).show();/
/
display thecurrent
state
for
switch's
}
});
}
}
Output:
NowstarttheAVDinEmulatorandruntheApp.YouwillseetwoswitchandoneButton.Now
changethestateoftheswitch(i.e.eithercheckedorunchecked)andclickontheButton.You
willseethestatedisplayedonscreenasToast.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
205
RadioButton&RadioGroup
InAndroid,RadioButtonaremainlyusedtogetherinaRadioGroup.InRadioGroupcheckingthe
oneradiobuttonoutofseveralradiobuttonaddedinitwillautomaticallyuncheckedallthe
others.Itmeansatonetimewecancheckedonlyoneradiobuttonfromagroupofradio
buttonswhichbelongtosameradiogroup.ThemostcommonuseofradiobuttonisinQuiz
App.
RadioButonisatwostatebuttonthatcanbecheckedorunchecked.Ifaradiobuttonis
uncheckedthenausercancheckitbysimplyclickingonit.OnceaRadiaButtonischeckedby
useritcan’tbeuncheckedbysimplypressingonthesamebutton.Itwillautomatically
uncheckedwhenyoupressanyotherRadioButtonwithinsameRadioGroup.
ImportantNote:RadioGroupisawidgetusedinAndroidforthegroupingofradiobuttons
andprovidethefeatureofselectingonlyoneradiobuttonfromtheset.Whenausertryto
selectanyotherradiobuttonwithinsameradiogroupthepreviouslyselectedradiobuttonwill
beautomaticallyunchecked.
RadioGroupAndRadioButtoncodeinXML:
<RadioGroup
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content">
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
/>
<RadioButton
android:id
="
@+id/simpleRadioButton1"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
206
ndroid:layout_width
a ="wrap_content"
android:layout_height
="wrap_content"
/>
</RadioGroup>
CheckingCurrentStateOfRadioButton:
YoucancheckthecurrentstateofaradiobuttonprogrammaticallybyusingisChecked()
method.ThismethodreturnsaBooleanvalueeithertrueorfalse.ifitischeckedthenreturns
trueotherwisereturnsfalse.Belowisanexamplecodewithexplanationinwhichwechecked
thecurrentstateofaradiobutton.
/*Add
in Oncreate()funtionaftersetContentView()*/
RadioButton
simpleRadioButton= (
RadioButton
)findViewById
(R.
id
.s
impleRadioButton
);
/
/
initiate a
radiobutton
BooleanR
adioButtonState =
simpleRadioButton .isChecked
();
/
/ check
current
state
ofa
radio
button(true or
false).
AttributesofRadioButtonInAndroid:
Nowlet’s wediscussimportantattributesthathelpsustocreateabeautifulradiobuttoninxml
file(layout).
1.id:idisanattributeusedtouniquelyidentifyaradiobutton.
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
207
2.checked:c heckedattributeinradiobuttonisusedtosetthecurrentstateofaradiobutton.
Wecansetiteithertrueorfalsewheretrueshowsthecheckedstateandfalseshowsunchecked
stateofaradiobutton.Asusualdefaultvalueofcheckedattributeisfalse.Wecanalsosetthe
currentstateinJAVA.
Belowwesettruevalueforcheckedattributewhichsetsthecurrentstatetocheckedofa
Button.
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:checked
="
true"
/><
!--
set
thecurrent
state
of
the
radio
button-->
SettingcheckedStateOfRadioButtonInJavaClass:
BelowcodesetthecurrentstateofRadioButtontocheckedprogrammatically.
/*Add
inOncreate()funtion
after setContentView()*/
//
initiatea
radiobutton
RadioButton
simpleRadioButton= (
RadioButton)
findViewById
(R
.i
d
.s
impleRadioButton
);
//
setthe
currentstate
of
aradio button
simpleRadioButton.s
etChecked(t
rue );
3.text:textattributeisusedtosetthetextinaradiobutton.Wecansetthetextbothways
eitherinXMLorinJAVAclass.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
208
Belowistheexamplecodewithexplanationincludedinwhichwesetthetext“Iama
radiobutton”ofa radiobutton.
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:checked
="
true"
android:layout_centerHorizontal
="
true"
android:text
="
I
am
aradiobutton" /
><
!--
displayed
text
of
radio
button-->
SettingtextofRadioButtonInJavaclass:
Belowwesetthetextofaradiobuttonprogrammatically:
/*Add
in
Oncreate()
funtion
after
setContentView()*/
RadioButton
simpleRadioButton
=(
RadioButton
)
findViewById
(R
.i
d
.s
impleRadioButton);
simpleRadioButton
.s
etText
("
I
am
a
radiobutton"
);
/
/
displayed text
of
radio
button
4.gravity:Thegravityattributeisanoptionalattributewhichisusedtocontrolthealignment
oftextlikeleft,right,center,top,bottom,center_vertical,center_horizontaletc.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
209
Belowistheexamplecodewithexplanationincludedinwhichwesetthecentergravityforthe
textofaradiobutton.
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:checked
="
true"
android:text
="
I
am
aButton"
android:gravity
="
center" />
<
!--
center
gravity
of
the
text-->
5.textColor:t extColorattributeisusedtosetthetextcolorofaradiobutton.Colorvalueisin
theformof“#argb”,“#rgb”,“#rrggbb”,or“#aarrggbb”.
Belowwesettheredcolorforthedisplayedtextofaradiobutton.
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:checked
="
true"
android:layout_centerHorizontal
="
true"
android:text
="
Male"
android:textColor
="
#f00" /
>
<!--red
color
for
displayed
text-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
210
SettingtextColorofRadioButtontextInJavaclass:
Belowwesetthetextcolorofaradiobuttonprogrammatically.
/*Add
in
Oncreate()
funtion
after setContentView()*/
RadioButton
simpleRadioButton=
(R
adioButton)
findViewById
(R
.i
d
.s
impleRadioButton
);
//
initiate
radio
button
simpleRadioButton
.s
etTextColor
(Color.R
ED
);
/
/red
color
fordisplayed
text
of
radio
button
6.textSize:t extSizeattributeisusedtosetthesizeofthetextofaradiobutton.Wecanset
thetextsizeinsp(scaleindependentpixel)ordp(densitypixel).
Belowwesetthe25spsizeforthetextofaradiobutton.
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:checked
="
true"
android:layout_centerHorizontal
="
true"
android:text
="
AbhiAndroid"
android:textColor
="
#f00"
android:textSize
="25sp"/><
!--setting t
ext
size-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
211
SettingtextSizeOfRadioButtonTextInJavaclass:
Belowwesetthetextsizeofaradiobuttonprogrammatically:
/*Add
in
Oncreate()
funtion
aftersetContentView()*/
RadioButton
simpleRadioButton=
(
RadioButton
)
findViewById(R
.i
d.s
impleRadioButton
);/
/
initiate
radio
button
simpleRadioButton
.s
etTextSize
(2
5
);/
/
set
25spdisplayed
text size
of
radio
button
7.textStyle:t extStyleattributeisusedtosetthetextstyleofthetextofaradiobutton.The
possibletextstylesarebold,italicandnormal.Ifweneedtousetwoormorestylesforatext
viewthen“|”operatorisusedforthat.
Belowistheexamplecodewithexplanationincludedinwhichwesettheboldanditalictext
stylesfortextofaradiobutton.
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:checked
="
true"
android:textSize
="25sp"
android:layout_centerHorizontal
="
true"
android:text
="
Male"
android:textColor
="
#f00"
android:textStyle
="
bold|italic" /><
!--bold
and
italic
text
style-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
212
8.background:backgroundattributeisusedtosetthebackgroundofaradiobutton.Wecan
setacolororadrawableinthebackgroundofaradiobutton.
Belowwesettheblackcolorforthebackgroundandredcolorforthedisplayedtextofaradio
button
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:checked
="
true"
android:textSize
="25sp"
android:textStyle
="
bold|italic"
android:padding
="
20dp"
android:layout_centerHorizontal
="true"
android:text
="
Male"
android:textColor
="
#f00"
android:background
="#000"/>
<
!--black
background
for
radio
button-->
.
SettingBackgroundOfRadioButtonInJavaclass:
Belowwesetthebackgroundcolorofaradiobuttonprogrammatically.
/*Add
in
Oncreate()
funtion
aftersetContentView()*/
RadioButton
simpleRadioButton=
(
RadioButton
)
findViewById
(R
.i
d
.s
impleRadioButton
);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
213
simpleRadioButton
.s
etBackgroundColor
(C
olor
.B
LACK
);
9.padding:p
addingattributeisusedtosetthepaddingfromleft,right,toporbottom.
paddingRight:setthepaddingfromtherightsideoftheradiobutton.
paddingLeft:setthepaddingfromtheleftsideoftheradiobutton.
paddingTop:s etthepaddingfromthetopsideoftheradiobutton.
paddingBottom:setthepaddingfromthebottomsideoftheradiobutton.
Padding:s etthepaddingfromtheallside’softheradiobutton.
Belowwesetpaddingattributeof20dppaddingfromalltheside’softheradiobutton.
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:checked
="
true"
android:textSize
="25sp"
android:textStyle
="
bold|italic"
android:layout_centerHorizontal
="true"
android:text
="
AbhiAndroid"
android:textColor
="
#f00"
android:padding
="
40dp"/><
!--40dppadding
from
all
the
sides
of
radio
button-->
10.drawableBottom,drawableTop,drawableLeftAnddrawableRight:These
attributedrawthedrawabletothebelowofthetextofRadioButton.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
214
BelowwesettheicontotherightofthetextofaRadioButton.
<RadioButton
android:id
="
@+id/simpleRadioButton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:checked
="
true"
android:textSize
="25sp"
android:padding
="
20dp"
android:layout_centerHorizontal
="
true"
android:text
="
AbhiAndroid"
android:textColor
="
#f00"
android:drawableRight
="@drawable/ic_launcher"
/
>
<
!--
drawable
icon
at
the
right
of
radio
button-->
ExampleOfRadioButtonAndRadioGroupinAndroidStudio:
BelowistheexampleofRadiobuttoninAndroidwherewedisplayfiveradiobuttonswith
backgroundandotherattributes.TheradiobuttonsareusedtoselectyourfavoriteWWE
superstarwithone“submit”button.Belowisthefinaloutput,downloadcodeandstepbystep
explanationoftutorial:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
215
Step1:C
reateanewprojectandnameitRadioButtonExample
SelectFile->New->NewProjectandFilltheformsandclick“Finish”button.
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthisstepweopenanxmlfileandaddthecodefordisplaying5RadioButtonandonenormal
button.
<LinearLayout
x
mlns: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"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
=".MainActivity" >
<LinearLayout
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
216
ndroid:layout_width
a ="
fill_parent"
android:layout_height
="wrap_content"
android:background
="
#e0e0e0"
android:orientation
="vertical">
<TextView
android:layout_width="
wrap_content"
android:layout_height="wrap_content"
android:text
="
Selectyour favouritewwe
SuperStar
::
"
android:textColor
="#000"
android:textSize
="
20sp"
android:textStyle
="bold" /
>
<RadioGroup
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
>
<RadioButton
android:id
="
@+id/johnCena"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_marginLeft
="20dp"
android:layout_marginTop
="
10dp"
android:checked
="
true"
android:text
="
@string/johnCena"
android:textColor
="
#154"
android:textSize
="20sp"
android:textStyle
="
bold" /
>
<RadioButton
android:id
="
@+id/randyOrton"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_marginLeft
="
20dp"
android:layout_marginTop
="10dp"
android:checked
="
false"
android:text
="
@string/randyOrton"
android:textColor
="
#154"
android:textSize
="20sp"
android:textStyle
="
bold" /
>
<RadioButton
android:id
="
@+id/romanReigns"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_marginLeft
="
20dp"
android:layout_marginTop
="10dp"
android:checked
="
false"
android:text
="
@string/romanReigns"
android:textColor
="
#154"
android:textSize
="20sp"
android:textStyle
="
bold" /
>
<RadioButton
android:id
="
@+id/goldBerg"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:layout_marginLeft
="
20dp"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
217
ndroid:layout_marginTop
a ="10dp"
android:checked
="
false"
android:text
="@string/goldBerg"
android:textColor
="
#154"
android:textSize
="20sp"
android:textStyle
="
bold"/
>
<RadioButton
android:id
="
@+id/sheamus"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_marginLeft
="
20dp"
android:layout_marginTop
="10dp"
android:checked
="
false"
android:text
="
@string/sheamus"
android:textColor
="
#154"
android:textSize
="20sp"
android:textStyle
="
bold" /
>
</RadioGroup>
<Button
android:id
="
@+id/submitButton"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_gravity ="center"
android:layout_margin ="20dp"
android:background ="#0f0"
android:padding="
10dp"
android:text="
Submit"
android:textColor ="
#fff"
android:textSize="20sp"
android:textStyle ="
bold" /
>
</LinearLayout>
</LinearLayout>
Step3:O
pen src->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodetoinitiatetheRadioButtonandnormal
button.Wealsoperformclickeventonbuttonanddisplaytheselectedsuperstar’snameby
usingaToast.
package
example
.gb
.radiobuttonexample;
import
android.s
upport .v
7.a
pp
.A
ppCompatActivity
;
import
android.o
s.B
undle;
import
android.v
iew .V
iew;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
218
import
android .w
idget .B
utton ;
import
android .w
idget .R
adioButton ;
import
android .w
idget .T
oast ;
publicc
lassMainActivity extends A
ppCompatActivity {
RadioButton
johnCena , randyOrton ,goldBerg ,romanReigns ,
sheamus ;
String
selectedSuperStar ;
Button
submit ;
@Override
protected
void
onCreate (Bundle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.l
ayout .a
ctivity_main );
j
ohnCena= (
RadioButton )findViewById (R.
id
.johnCena );
r
andyOrton= (R
adioButton )findViewById (R.
id
.randyOrton );
g
oldBerg= (
RadioButton )findViewById (R.
id
.goldBerg );
r
omanReigns =(R
adioButton )findViewById (R
.i
d.romanReigns );
s
heamus= (R
adioButton )findViewById (R
.i
d.sheamus );
s
ubmit= (Button )findViewById (R.
id
.s
ubmitButton );
s
ubmit .s
etOnClickListener (n
ew V
iew .O
nClickListener (){
@Override
public v
oid onClick (Viewv)
{
if
(
randyOrton .isChecked ()){
s
electedSuperStar= randyOrton .g
etText ().toString ();
}e
lseif(s
heamus .isChecked ()){
s
electedSuperStar= sheamus .getText ().
toString ();
}e
lseif(j
ohnCena .i
sChecked ()) {
s
electedSuperStar= johnCena .g
etText ().toString ();
}e
lseif(r
omanReigns .isChecked ()) {
s
electedSuperStar= romanReigns .getText ().toString ();
}e
lseif(g
oldBerg .i
sChecked ()) {
s
electedSuperStar= goldBerg .g
etText ().toString ();
}
Toast
.makeText (g
etApplicationContext (),
selectedSuperStar ,
Toast
.LENGTH_LONG ).show ();//print the value ofselected super star
}
});
}
}
Step4:O
penres->values->strings.xml
InthisstepweopenStringfilewhichisusedtostorestringdataoftheapp.
<resources>
<string
n
ame
="app_name"
>RadioButtonExample </string>
<string
n
ame
="hello_world">Helloworld!
</string>
<string
n
ame
="action_settings" >S
ettings</string>
<string
n
ame
="randyOrton">R
andy Orton
</string>
<string
n
ame
="johnCena"
>JohnCena</string>
<string
n
ame
="romanReigns">RomanReigns
</string>
<string
n
ame
="goldBerg"
>GoldBerg</string>
<string
n
ame
="sheamus"
>S
heamus </string>
</resources>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
219
RunTheApp:
NowruntheAppinEmulatorandyouwillsee5RadioButtoninRadioGrouplistingWWE
superstarname.NowchooseyourfavoriteoneandclickonSubmitButton.Thenamewillbe
displayedonScreen.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
220
RatingBar
RatingBarisusedtogettheratingfromtheappuser.Ausercansimplytouch,dragorclickon
thestarstosettheratingvalue.Thevalueofratingalwaysreturnsafloatingpointnumber
whichmaybe1.0,2.5,4.5etc.
InAndroid,RatingBarisanextensionofProgressBarandSeekBarwhichshowsaratinginstars.
RatingBarisasubclassofAbsSeekBarclass.
Theg
etRating()methodofandroidRatingBarclassreturnstheratingnumber.
RatingBarcodeinXML:
<RatingBar
android:id
="@+id/simpleRatingBar"
android:layout_width="
wrap_content"
android:layout_height="wrap_content"/
>
MethodsUsedinRatingBar:
getRating():
YoucangettheratingnumberfromaRatingBarbyusinggetRating()method.Thismethod
returnsaFloatingPointnumber.BelowwegetthecurrentratingnumberfromaRatingBar.
/*Add
in
Oncreate()
funtion
aftersetContentView()*/
RatingBar
simpleRatingBar=
(
RatingBar
)
findViewById
(R
.i
d
.s
impleRatingBar
);
/
/
initiate
a
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
221
ratingbar
Float
ratingNumber=
simpleRatingBar
.g
etRating
();
/
/
get
rating
number
from
a
rating
bar
getNumStars():
YoucangetthenumberofstarsofaRatingBarbyusinggetNumstars()method.Thismethod
returnsintvalue.InbelowcodewegetthetotalnumberofstarsofaRatingBar.
/*Addin
Oncreate()
funtion
aftersetContentView()*/
RatingBar
simpleRatingBar=
(
RatingBar
)
findViewById(R
.i
d
.s
impleRatingBar
);
/
/
initiatea
ratingbar
int
numberOfStars=
simpleRatingBar.g
etNumStars
();
/
/gettotal
number
of
starsof
rating
bar
AttributesUsedinRatingBar:
Nowlet’swediscusssomeimportantattributethathelpsustoconfigureaRatingBarinXMLfile
(layout).
1.id:idisanattributeusedtouniquelyidentifyaratingbar.
<RatingBar
android:id
="@+id/simpleRatingBar"
android:layout_width="
wrap_content"
android:layout_height="wrap_content"
/>
2.background:backgroundattributeisusedtosetthebackgroundofaRatingBar.Wecanset
acolororadrawableinthebackgroundofaratingbar.
Belowwesettheredcolorforthebackgroundofaratingbar.
<RatingBar
a
ndroid
:i
d
="
@+id/simpleRatingBar"
a
ndroid
:l
ayout_width="
wrap_content"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:b
ackground
="
#f00" />
<
!--
redcolorf
or
the
background
of
rating
bar
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
222
SettingBackgroundofRatingBarInJavaclass:
RatingBar
simpleRatingBar=
(
RatingBar
)
findViewById
(R
.i
d
.s
impleRatingBar
);
/
/initiate
a
rating
bar
simpleRatingBar
.s
etBackgroundColor(C
olor
.R
ED
);
/
/
set
backgroundcolor
for
a
rating
bar
3.numStars:n
umStarsattributeisusedtosetthenumberofstars(orratingitems)tobe
displayedinaratingbar.Bydefaultaratingbarshowsfivestarsbutwecanchangeitusing
numStarsattribute.
numStarsmusthaveaintegernumberlike1,2etc.
Belowwesetnumstarsvalueto7ofRatingBar.
<RatingBar
android:id
="
@+id/simpleRatingBar"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:numStars
="7"
/
><!--
number
ofstars
to
be
displayed-->
SettingnumStarsofRatingBarInJavaclass:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
223
RatingBar
simpleRatingBar=
(R
atingBar
)findViewById
(R.
id
.s
impleRatingBar
);
/
/
initiate
a
rating
bar
simpleRatingBar
.s
etNumStars
(7
);
/
/
set
totalnumber
ofstars
4.rating:Ratingattributesetthedefaultratingofaratingbar.Itmustbeafloatingpoint
number.
Belowwesetdefaultratingto3.5foraratingbar.
<RatingBar
android:id
="
@+id/simpleRatingBar"
android:layout_width
="wrap_content"
android:layout_height
="
wrap_content"
android:rating
="
3.5"
/
><
!--
default
rating-->
SettingDefaultRatingofRatingBarInJavaclass:
/*Add
inOncreate()
funtionaftersetContentView()*/
RatingBar
simpleRatingBar=(
RatingBar)
findViewById
(R
.i
d
.s
impleRatingBar
);
/
/
initiate
a
ratingbar
simpleRatingBar.s
etRating
((float)3
.5
);/
/
set
defaultrating
5.padding:paddingattributeisusedtosetthepaddingfromleft,right,toporbottom.
paddingRight:setpaddingfromtherightsideoftheratingbar.
paddingLeft:setpaddingfromtheleftsideoftheratingbar.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
224
paddingTop:s etpaddingfromthetopsideoftheratingbar.
paddingBottom:setthepaddingfromthebottomsideoftheratingbar.
Padding:s etthepaddingfromtheallside’softheratingbar.
Belowwesetthe20dppaddingfromalltheside’softheratingbar.
<RatingBar
android:id
="
@+id/simpleRatingBar"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:rating
="
2.5"
android:numStars
="
6"
android:background
="
#f00"
android:padding
="20dp"/><
!--20dp
padding
from
all
the
sides
of
rating
bar-->
RatingBarExampleInAndroidStudio:
BelowistheexampleofRatingBarinAndroidwherewedisplayedaRatingBarwithfivestars
andasubmitbutton.Wheneverauserclickonthebuttonvalueoftotalnumberofstarsand
valueofratingisshownbyusingaToastonscreen.Belowisthefinaloutput,downloadcode
andstepbysteptutorial:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
225
ImportantNote:W
ecanalsocreatecustomratingbarinAndroidinwhichwecanchangethe
starimageslikefilledoremptystar.Wediscussedthisinnextexample,sodon’tmissit.
Step1:CreateanewprojectandnameitRatingBarExample
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
a
nd
F
ill
the
formsa
nd
click"
Finish"
button.
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode
Inthisstepweopenanxmlfileandaddthecodefordisplayingaratingbarwithfivenumberof
starsand“2”valuefordefaultratingandonesubmitbutton.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools
="
http://schemas.android.com/tools"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft ="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop ="
@dimen/activity_vertical_margin"
t
ools
:c
ontext="
.MainActivity">
<
RatingBar
a
ndroid
:i
d="@+id/simpleRatingBar"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
226
a
ndroid
:l
ayout_width="wrap_content"
a
ndroid
:l
ayout_height ="
wrap_content"
a
ndroid
:l
ayout_centerHorizontal ="true"
a
ndroid
:l
ayout_marginTop ="
60dp"
a
ndroid
:b
ackground
="#0f0"
a
ndroid
:p
addingLeft="
5dp"
a
ndroid
:p
addingRight="5dp"
a
ndroid
:r
ating
="
2"
/
>
<
Button
a
ndroid
:i
d="@+id/submitButton"
a
ndroid
:l
ayout_width ="
200dp"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_centerInParent ="
true"
a
ndroid
:b
ackground ="#f00"
a
ndroid
:p
adding ="
10dp"
a
ndroid
:t
ext ="
Submit"
a
ndroid
:t
extColor ="
#fff"
a
ndroid
:t
extSize ="20sp"
a
ndroid
:t
extStyle ="
bold" /
>
</RelativeLayout>
Step3:O
pensrc->package->MainActivity.java
InthisstepweopenMainActivitywhereweaddthecodetoinitiatetheRatingBar&buttonand
thenweperformclickeventonbuttonanddisplaythetotalnumberofstarsandratingbyusing
atoast.
package
example.gb
.ratingbarexample ;
import
android .s
upport .v
7.app.A
ppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .M
enu;
import
android .v
iew .M
enuItem ;
import
android .v
iew .V
iew;
import
android .w
idget .R
atingBar ;
import
android .w
idget .B
utton ;
import
android .w
idget .T
oast ;
public
c
lassM
ainActivity extends A
ppCompatActivity {
@Override
protected
voidonCreate (Bundle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .a
ctivity_main );
//
initiate rating barand abutton
final
RatingBar
simpleRatingBar= (
RatingBar
)findViewById
(R
.i
d
.s
impleRatingBar
);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
227
utton
B
submitButton= (
Button
)findViewById (R
.i
d.s
ubmitButton);
//
perform click eventon
button
s
ubmitButton .s
etOnClickListener (n
ewV
iew.O
nClickListener ()
{
@Override
public v
oid
onClick (V
iew
v)
{
//
get valuesandthen displayed in
atoast
String
totalStars= "
Total Stars::"+simpleRatingBar .g
etNumStars ();
String
rating="Rating ::"+
simpleRatingBar .g
etRating ();
Toast
.makeText(getApplicationContext (),
totalStars+"
\n" +
rating
,
Toast
.LENGTH_LONG ).
show ();
}
});
}
}
Output:
NowstarttheAVDinEmulatorandruntheApp.Youwillseetheratingoptiononscreen.Select
yourratingandclickonSubmit.YourratingwillbedisplayedonscreenasToast.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
228
CustomRatingBarExampleInAndroidStudio:
InthebelowexampleofcustomratingbarinAndroid,wedisplayedaratingbarwithfive
customstarsandasubmitbutton.Wheneverauserclickonthebuttonvalueoftotalnumberof
starsandvalueofratingisshownbyusingaToast.Belowisthefinaloutput,downloadcodeand
stepbystepexplanationofCustomRatingBar.
Step1:C
reateanewprojectandnameitCustomRatingBarExample
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
-
>
t
hen
F
ill
the
formsa
nd
click"
Finish"
button.
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode
Inthisstepweopenanxmlfileandaddthecodefordisplayingacustomratingbarwithfive
numberofstarsand“2.5”valuefordefaultratingandonesubmitbutton.
<RelativeLayout
x
mlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:background
="
#fff"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
229
ndroid:paddingBottom
a ="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
="
.MainActivity" >
<RatingBar
android:id
="
@+id/simpleRatingBar"
style
="
@
style
/c
ustomRatingBar "
android:layout_width
="
wrap_content"
android:layout_height
="60dp"
android:layout_centerHorizontal
="true"
android:layout_marginTop
="
60dp"
android:background
="
#0f0"
android:rating
="
2.5"/
>
<Button
android:id
="
@+id/submitButton"
android:layout_width
="
200dp"
android:layout_height
="wrap_content"
android:layout_centerInParent
="
true"
android:background
="#f40"
android:padding
="
10dp"
android:text
="
Submit"
android:textColor
="
#fff"
android:textSize
="20sp"
android:textStyle
="
bold" /
>
</RelativeLayout>
Step3:O
pensrc->package->MainActivity.java
InthisstepweopenMainActivitywhereweaddthecodetoinitiatetheRatingBar&buttonand
thenperformclickeventonbuttonanddisplaythetotalnumberofstarsandratingbyusinga
Toast.
package
example.gb
.customratingbarexample ;
import
android .s
upport .v
7.app.A
ppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .M
enu;
import
android .v
iew .M
enuItem ;
import
android .v
iew .V
iew;
import
android .w
idget .R
atingBar ;
import
android .w
idget .B
utton ;
import
android .w
idget .T
oast ;
public
c
lassM
ainActivity extends A
ppCompatActivity {
@Override
protected
voidonCreate (Bundle
savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .activity_main );
//
initiate rating barand a
button
final
RatingBar
simpleRatingBar= (
RatingBar
)findViewById(R
.i
d
.simpleRatingBar
);
Button
submitButton= (B
utton )
findViewById (R
.i
d.s
ubmitButton);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
230
/
/ perform click event
onbutton
s
ubmitButton .s
etOnClickListener (n
ewV
iew.O
nClickListener()
{
@Override
publicv
oid
onClick(View
v)
{
//
get valuesandthen displayed in
atoast
String
totalStars= "
Total Stars::"+
simpleRatingBar .g
etNumStars();
String
rating="Rating ::"+
simpleRatingBar.g
etRating ();
Toast
.makeText(g
etApplicationContext (),
totalStars+"
\n"+
rating
,
Toast
.LENGTH_LONG ).
show ();
}
});
}
}
Step4:Openres->values->styles.xml
Inthisstepweaddthecodefordisplayingcustomstarsforrating.Todothatinthisstyles.xml
filewesetancustomxmlfilefromdrawableandsettheheightandwidthforthatitem.
<resources>
<!--
Baseapplication
theme.-->
<style
n
ame="
AppTheme"
p
arent="
Theme.AppCompat.Light.DarkActionBar">
<!--
Customize
yourtheme
here.-->
</style>
<style
n
ame="
customRatingBar"p
arent
="@android:style/Widget.RatingBar">
<item
n
ame
="
android:progressDrawable" >@
drawable/customratingstars</item>
<item
n
ame
="
android:minHeight">2
0dip</item>
<item
n
ame
="
android:maxHeight">2
0dip</item>
</style>
</resources>
Step5:C
reateanewdrawableXMLfile–>customratingstars.xml
InthisstepwecreateanewdrawableXMLfile,inwhichwesettheiconsforfilledandempty
stars.Asshowninbelowcodesnippetemptyandfilledaretwodifferenticonssetfrom
drawable.
<?
xml
version="1.0"
encoding="
utf-8"
?>
<layer-listx
mlns:android ="
http://schemas.android.com/apk/res/android"
>
<item
a
ndroid:id ="
@android:id/background"
android:drawable
="
@drawable/empty"
/
>
<item
a
ndroid:id ="
@android:id/secondaryProgress"
android:drawable
="
@drawable/empty"
/
>
<item
a
ndroid:id ="
@android:id/progress"
android:drawable
="
@drawable/filled"
/>
</layer-list>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
231
Output:
NowstarttheAVDinEmulatorandruntheApp.Youwillseecustomstarratingoptionon
screen.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
232
WebView
InAndroid,WebViewisaviewusedtodisplaythewebpagesinapplication.Thisclassisthe
basisuponwhichyoucanrollyourownwebbrowserorsimplyuseittodisplaysomeonline
contentwithinyourActivity.WecanalsospecifyHTMLstringandcanshowitinsideour
applicationusingaWebView.Basically,WebViewturnsapplicationintoawebapplication.
InordertoaddWebViewinyourapplication,youhavetoadd<WebView>elementtoyour
XML(layout)fileoryoucanalsoadditinjavaclass.
<WebView
android:id
="
@+id/simpleWebView"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"/
>
InternetPermissionRequiredForWebview:
ImportantNote:I norderforActivitytoaccesstheInternetandloadthewebpagesina
WebView,wemustaddtheinternetpermissionstoourAndroidManifestfile(Manifest.xml).\
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
233
Belowcodedefinetheinternetpermissioninourmanifestfiletoaccesstheinternetinour
application.
<!--Add
this
before
applicationtag
in
AndroidManifest.xml-->
<uses-permission
a
ndroid:name
="android.permission.INTERNET"
/
>
MethodsofWebViewInAndroid:
Let’sdiscusssomecommonmethodsofaWebviewwhichareusedtoconfigureawebviewin
ourapplication.
loadUrl()–L
oadawebpageinourWebView
loadUrl
(S
tring
url)
Thisfunctionisusedtoloadawebpageinawebviewofourapplication.Inthismethodwe
specifytheurlofthewebpagethatshouldbeloadedinawebview.
Belowweloadaurl:http://abhiandroid.com/ui/i nourapplication.
/*Add
in Oncreate()funtion
after
setContentView()*/
//
initiate a
webview
WebView
simpleWebView =(
WebView
)
findViewById(R
.i
d
.s
impleWebView
);
//
specify theurl
of
the
web
pagein
loadUrlfunction
simpleWebView .l
oadUrl("
http://abhiandroid.com/ui/" );
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
234
2.loadData()–LoadStaticHtmlDataonWebView
loadData
(S
tring
data
,S
tring
mimeType
,S
tring
encoding
)
ThismethodisusedtoloadthestaticHTMLstringinawebview.loadData()functiontakes
htmlstringdata,mime-typeandencodingparamasthreeparameters.
BelowweloadthestaticHtmlstringdatainourapplicationofawebview.
/*Add
in Oncreate() funtionaftersetContentView()*/
//
initiate a
web view
WebView
webView= (
WebView)
findViewById (R
.i
d.s
impleWebView);
//
static htmlstring data
String
customHtml= "
<html><body><h1>Hello, AbhiAndroid</h1>"+
"<h1>Heading
1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +
"<p>This
isasampleparagraphofstaticHTMLIn
Web
view</p>" +
"</body></html>"
;
//
loadstatic htmldataon
aweb
view
webView
.loadData (c
ustomHtml ,"text/html","UTF-8");
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
235
3.LoadRemoteURLonWebViewusingWebViewClient:
WebViewClienthelpustomonitoreventinaWebView.YouhavetoOverridethe
shouldOverrideUrlLoading()method.Thismethodallowustoperformourownactionwhena
particularurlisselected.OnceyouarereadywiththeWebViewClient,youcansetthe
WebViewClientinyourWebViewusingthesetWebViewClient()method.
BelowweloadaurlbyusingwebviewclientinaWebView.
/*Addin Oncreate() funtion aftersetContentView()*/
//initiate awebview
simpleWebView= (W
ebView )
findViewById (R.
id
.simpleWebView );
//setweb view client
simpleWebView .s
etWebViewClient (new
MyWebViewClient ());
//string url which youhavetoloadinto aweb
view
S
tring
url= "http://abhiandroid.com/ui/" ;
simpleWebView .g
etSettings ().setJavaScriptEnabled (t
rue);
simpleWebView .l
oadUrl (u
rl);
//
load theurl on
theweb view
}
/
/custom webview clientclass whoextends WebViewClient
p
rivate classMyWebViewClient e
xtends W
ebViewClient {
@
Override
p
ublic b
oolean
shouldOverrideUrlLoading (W
ebView view
,String
url
){
view.l
oadUrl (url);
/
/loadtheurl
r
eturn t
rue ;
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
236
4.canGoBack()–Movetoonepagebackifabackhistoryexist
Thismethodisusedtospecifywhetherthewebviewhasabackhistoryitemornot.This
methodreturnsaBooleanvalueeithertrueorfalse.IfitreturnstruethengoBack()methodis
usedtomoveonepageback.
Belowwecheckwhetherawebviewhasbackhistoryornot.
//
initiate
a
webview
WebView
simpleWebView=(
WebView)f
indViewById(R
.i
d
.s
impleWebView
);
//
checks
whethera
webview
hasa
back
historyitem
or
not
Boolean
canGoBack
=s
impleWebView .canGoBack
();
5.canGoForward()–M
oveonepageforwardifforwardhistoryexist
Thismethodisusedtospecifywhetherthewebviewhasaforwordhistoryitemornot.This
methodreturnsaBooleanvalueeithertrueorfalse.IfitreturnstruethengoForword()method
isusedtomoveonepageforword.
Belowwecheckwhetherawebviewhasforwardhistoryornot.
//
initiatea
web
view
W
ebView
simpleWebView=(
WebView
)f
indViewById(R
.i
d.s
impleWebView);
//
checkswhether
a
web
view
hasa
forward
history item
or
not
B
oolean
canGoForword=s
impleWebView.c
anGoForward ()
;
6.clearHistory()–c leartheWebViewhistory
Thismethodisusedtoclearthewebviewforwardandbackwardhistory.
BelowwecleartheforwordandbackwordhistoryofaWebView.
WebView
simpleWebView
=(
WebView
)f
indViewById
(R
.i
d
.s
impleWebView
);
/
/
initiate
a
web
view
simpleWebView
.c
learHistory
();
/
/
clear
the
forwardand
backward
history
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
237
WebViewExampleInAndroidStudio:
HereinthisWebViewexampleweshowtheuseofwebviewinourapplication.Todothatwe
displaytwobuttonsoneisfordisplayingawebpageandotherisfordisplayingstaticHTML
datainawebview.Belowisthefinaloutput,downloadcodeandstepbystepexplanation:
Step1:C
reateanewprojectandnameitWebViewExample
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
…t
hen
F
ill
the
formsa
nd
click"
Finish"
button.
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepweopenanXMLfileandaddthecodefordisplayingtwobuttonsandaWebviewin
ourxmlfile(layout)
<LinearLayout
x
mlns: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"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
238
ndroid:paddingBottom
a ="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
="
.MainActivity" >
<LinearLayout
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:orientation
="
horizontal"
android:weightSum
="
2">
<Button
android:id
="
@+id/loadWebPage"
android:layout_width ="
0dp"
android:layout_height ="wrap_content"
android:layout_marginRight ="
10dp"
android:layout_weight ="1"
android:background="#444"
android:text="
LoadWebPage"
android:textColor="#fff"
android:textSize="
14sp"
android:textStyle="bold" /
>
<Button
android:id
="
@+id/loadFromStaticHtml"
android:layout_width ="
0dp"
android:layout_height ="wrap_content"
android:layout_marginLeft ="10dp"
android:layout_weight ="1"
android:background="#444"
android:text="
LoadStatic HTML"
android:textColor="#fff"
android:textSize="
14sp"
android:textStyle="bold" /
>
</LinearLayout>
<WebView
android:id
="
@+id/simpleWebView"
android:layout_width
="
fill_parent"
android:layout_height
="fill_parent"
android:layout_marginTop
="
20dp"
android:scrollbars
="
none" /
>
</LinearLayout>
Step3:Open src->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodetoinitiatethewebviewandtwobuttons.
Outofthoseonebuttonisusedfordisplayingawebpageinawebviewandotheroneisusedto
loadastaticHTMLpageinwebview.
package
example
.gb
.w
ebviewexample
;
import
android.s
upport.v
7
.a
pp
.A
ppCompatActivity
;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
239
import
android .os.Bundle ;
import
android .support .v
7.widget .B
uttonBarLayout ;
import
android .view .Menu;
import
android .view .MenuItem ;
import
android .view .View;
import
android .webkit .W
ebView ;
import
android .webkit .W
ebViewClient ;
import
android .widget .B
utton ;
publicc
lass MainActivity extends A
ppCompatActivity i
mplements View
.OnClickListener {
WebView
simpleWebView ;
Button
loadWebPage ,loadFromStaticHtml ;
@Override
protected
v
oid onCreate (B
undle savedInstanceState ){
super
.o
nCreate (savedInstanceState );
s
etContentView (R.
layout .a
ctivity_main );
//
initiate buttons and aweb view
l
oadFromStaticHtml= (B
utton )findViewById (R.
id
.loadFromStaticHtml );
l
oadFromStaticHtml .setOnClickListener (this);
l
oadWebPage =(
Button )findViewById (R.
id
.loadWebPage );
l
oadWebPage .setOnClickListener (this);
s
impleWebView= (WebView )findViewById (R.
id
.simpleWebView );
}
@Override
public
v
oid onClick (V
iew v)
{
switch
(
v.
getId()) {
case R.
i
d.l
oadFromStaticHtml :
//
define static html text
String
customHtml= "<html><body><h1>Hello, AbhiAndroid</h1>" +
"<h1>Heading
1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +
"<p>This
isasample paragraph ofstaticHTML In
Web view</p>" +
"</body></html>"
;
s
impleWebView .l
oadData (customHtml ,"text/html" ,"UTF-8" );
/
/ load html
stringdata ina webview
break
;
case R.
i
d.l
oadWebPage :
s
impleWebView .s
etWebViewClient (n
ewMyWebViewClient ());
String
url= "http://abhiandroid.com/ui/" ;
s
impleWebView .g
etSettings ().setJavaScriptEnabled (t
rue );
s
impleWebView .l
oadUrl (u
rl);/
/ load a
web pagein
a
webview
break
;
}
}
private
c
lass MyWebViewClient e
xtends W
ebViewClient {
@Override
public
b
oolean shouldOverrideUrlLoading (WebView
view,S
tring
url){
v
iew .loadUrl (url);
return t
rue ;
}
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
240
Step4:O
penm
anifests->AndroidManifest.xml
InthisstepweopenManifestfileanddefinetheinternetpermissionforourapp.
<?
xml
version ="
1.0"
encoding ="utf-8"
?>
<manifest
xmlns:android ="
http://schemas.android.com/apk/res/android"
package
="
example.gb.webviewexample" >
<!--
defineinternet permission forourapp
-->
<uses-permission
a
ndroid:name ="
android.permission.INTERNET" /
>
<application
android:allowBackup
="true"
android:icon
="
@mipmap/ic_launcher"
android:label
="@string/app_name"
android:theme
="@style/AppTheme" >
<activity
android:name =".MainActivity"
android:label ="
@string/app_name" >
<intent-filter>
<action
a
ndroid:name ="android.intent.action.MAIN"/
>
<category
a
ndroid:name ="android.intent.category.LAUNCHER"
/
>
</intent-filter>
</activity>
</application>
</manifest>
Output:
NowstarttheAVDinEmulatorandruntheApp.ChooseeithertoopenwebpageorstaticHTML
inWebViewbyclickingonButton.WeopenstaticHTML.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
241
ConvertWebsiteIntoAppUsingWebView:
NowyouhavelearnWebView,sowhynottryconvertinganywebsiteintoAndroidApp?
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
242
AutocompleteTextview
InAndroid,AutoCompleteTextViewisaviewi.esimilartoEditText,exceptthatitdisplaysalist
ofcompletionsuggestionsautomaticallywhiletheuseristyping.Alistofsuggestionsis
displayedindropdownmenufromwhichusercanchooseanitemwhichactuallyreplacethe
contentofEditboxwiththat.
ItisasubclassofEditTextclasssowecaninheritallthepropertiesofEditTextina
AutoCompleteTextView.
AutoCompleteTextViewcodeinXML:
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:text="
This
isanAutoCompleteTextView"
/>
UsingArrayAdapterToDisplayTextValuesInAutoCompleteTextView:
TodisplaytheArraycontentinanautocompletetextviewweneedtoimplementAdapter.In
AutoCompleteTextViewwemainlydisplaytextvaluessoweuseArrayAdapterforthat.
ArrayAdapterInAndroid:
ArrayAdapterisusedwhenweneedlistofsingletypeofitemswhichisbackedbyanArray.For
example,listofphonecontacts,countriesornames.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
243
ArrayAdaptercode:
ArrayAdapter
(Context
context
,i
nt
resource
,i
nt
textViewResourceId
,
T[]
objects)
RetrievingtheValueFromAutoCompleteTextViewInJavaClass:
BelowcoderetrievethevaluefromaAutoCompleteTextViewinJavaclass.
AutoCompleteTextView
simpleAutoCompleteTextView=(
AutoCompleteTextView
)
findViewById
(R.
i
d
.s
impleAutoCompleteTextView
);
String
A
utoCompleteTextViewValue=
simpleAutoCompleteTextView .g
etText
().
toString
();
AttributesofAutoCompleteTextView:
Nowlet’s wediscussabouttheattributesthathelpsustoconfigureaAutoCompleteTextViewin
yourxmlfile.
1.id:idisanattributeusedtouniquelyidentifyatextAutoCompleteTextView.
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_height
="wrap_content"
android:layout_width
="match_parent"
/>
2.text:t extattributeisusedtosetthetextinaAutoCompleteTextView.Wecansetthetextin
XMLaswellasinthejavaclass.
Belowwesetthetext“Country”inaAutoCompleteTextView.
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:text
="
Country"
/><!--display
text
"Country"-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
244
3.gravity:Thegravityattributeisanoptionalattributewhichcontrolthealignmentofthe
textlikeleft,right,center,top,bottom,center_vertical,center_horizontaletc.
BelowwesettherightgravityfortextofaAutoCompleteTextView.
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:text
="
Country"
android:gravity
="
right"/>
<!--right
gravity
for
text-->
SettingTextOfAutoCompleteTextViewInJavaclass:
/*Add
in
Oncreate()
funtionafter
setContentView()*/
AutoCompleteTextView
autoCompleteTextView=
(
AutoCompleteTextView
)findViewById
(R
.i
d
.s
impleAutoCompleteTextView
);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
245
//display
text
Country
autoCompleteTextView
.setText
("
Country"
);
4.hint:h
intattributegivesthehinttotheuserthatwhatshouldheEnterinthis
AutoCompleteTextView.WheneverhestarttotypeinAutoCompleteTextViewthehint
willautomaticallydisappear.
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="
Enter
YourCountry
NameHere"
/
>
<!--display
hint-->
SettinghintForAutoCompleteTextViewInJavaclass:
/*Add
in
Oncreate()
funtionafter
setContentView()*/
AutoCompleteTextView
autoCompleteTextView=
(
AutoCompleteTextView
)findViewById
(R
.i
d
.s
impleAutoCompleteTextView );
autoCompleteTextView
.setHint
("
Enter
Your Name
Here"
);//display
hint
5.textColor:T
hisattributesetthecolorofatextinAutoCompleteTextView.Colorvaluecan
beintheformof“#argb”,“#rgb”,“#rrggbb”,or“#aarrggbb”.
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_width="
fill_parent"
android:layout_height="wrap_content"
android:text="
Country"
android:textColor="
#f00"/>
<!--red
color
for
text-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
246
SettingTextColorofAutoCompleteViewTextInJavaclass:
/*Add
in
Oncreate()
funtionafter
setContentView()*/
AutoCompleteTextView
simpleAutoCompleteTextView
=(
AutoCompleteTextView)f
indViewById
(R
.i
d
.s
impleAutoCompleteTextVie
w
);
simpleAutoCompleteTextView
.s
etTextColor(C
olor
.R
ED
);
//red
color
fortext
6.textColorHint:Thisattributeisusedtosetthecolorofdisplayedhint.
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="
Enter
YourName
Here"
android:textColorHint="#0f0"
/>
<!--green
color
for
hint-->
SettingColortoHintOfAutoCompleteTextViewInJavaclass:
/*Add
in
Oncreate()
funtion
after
setContentView()*/
AutoCompleteTextView
simpleAutoCompleteTextView
=(
AutoCompleteTextView
)findViewById
(R
.i
d
.s
impleAutoCompleteTextVie
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
247
w
);
//green
color
for
displayedhint
simpleAutoCompleteTextView
.s
etHintTextColor
(C
olor
.g
reen
(0
));
7.textSize:ThisattributesetthesizeoftextinAutoCompleteTextView.Wecansetthetext
sizeinsp(scaleindependentpixel)ordp(densitypixel).
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_width="
fill_parent"
android:layout_height="wrap_content"
android:text="
Country"
android:textSize="
25sp"/
>
<!--set
the
text
size-->
SettingTextSizeInJavaclass:
/*Add
in
Oncreate() funtionafter
setContentView()*/
AutoCompleteTextView
simpleAutoCompleteTextView =(
AutoCompleteTextView)f
indViewById
(R
.i
d
.s
impleAutoCompleteTextVie
w
);
//set
thetext
size
simpleAutoCompleteTextView .s
etTextSize(2
5
);
8.textStyle:t extStyleattributeisusedtogivetextstyleofaAutoCompleteTextView.Wecan
addbold,italicandnormalstyle.Ifwewanttousetwoormorestylesfora
AutoCompleteTextViewthen“|”operatorisusedforthat.
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:text
="
Country"
android:textSize
="
25sp"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
248
android:textStyle
="
bold|italic"
/>
<!--bold
and
italic
text
style-->
9.backgroundandpadding:backgroundattributeisusedtosetthebackgroundofa
AutoCompleteTextView.Wecansetacolororadrawableinthebackgroundofa
AutoCompleteTextView.
paddingattributeisusedtosetthepaddingfromleft,right,toporbottom.
Belowwesetblackcolorasbackground,whitecolorasdisplayedhintandset15dppadding
fromalltheside’sforAutoCompleteTextView.
<AutoCompleteTextView
android:id
="
@+id/simpleAutoCompleteTextView"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:background ="
#000"
android:hint="
Enter YourNameHere"
android:padding="
15dp"
android:textColorHint ="#fff"
android:textStyle ="
bold|italic" /
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
249
SettingBackgroundofAutoCompleteTextViewInJavaclass:
/*Add
in
Oncreate()
funtionafter
setContentView()*/
AutoCompleteTextView
simpleAutoCompleteTextView
=(
AutoCompleteTextView)f
indViewById
(R
.i
d
.s
impleAutoCompleteTextVie
w
);
simpleAutoCompleteTextView
.s
etBackgroundColor(C
olor
.B
LACK
);
//setblack
background
color
AutoCompleteTextViewExampleinAndroidStudio:
IntheexampleofAutoCompleteTextViewwedisplayaautocompletetextviewwithsuggestion
listwhichincludecountrylist.TofillthedataincountrylistweimplementanArrayAdapter.
Belowisthefinaloutput,downloadcodeandstepbysteptutorial:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
250
Step1:C
reateanewprojectandnameitAutoCompleteTextViewExample.
Step2:Openres->layout->activity_mail.xml(or)main.xmlandaddfollowingcode:
Inthisstepweopenanxmlfileandaddthecodefordisplayinganautocompletetextviewby
usingdifferentattributesaswediscussedearlierinthisarticle.
<?
xml
version
="
1.0"
encoding ="
utf-8"?>
<RelativeLayoutx
mlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
="abhiandroid.com.autocompletetextviewtexting.MainActivity" >
<AutoCompleteTextView
android:id
="@+id/simpleAutoCompleteTextView"
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:background
="#000"
android:hint
="Enter YourNameHere"
android:padding
="15dp"
android:textColorHint
="#fff"
android:textStyle
="bold|italic" />
</RelativeLayout>
Step3:O
penapp->package->MainActivity.java
InthisstepweopenMainActivitywhereweaddthecodetoinitiatetheautocompletetextview
andthenfillthedatainthesuggestionlistbyusinganArrayAdapter.
package
example.abhiandriod .a
utocompletetextviewexample ;
import
android .s
upport .v
7.app
.AppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .M
enu;
import
android .v
iew .M
enuItem ;
import
android .w
idget .A
rrayAdapter ;
import
android .w
idget .A
utoCompleteTextView ;
public
c
lassMainActivity extends A
ppCompatActivity {
String
[]
countryNameList= {
"India","
China"
,"
Australia","
New
Zealand"
,"
England"
,
"Pakistan"};
@Override
protected
v
oidonCreate (B
undle savedInstanceState ){
super
.o
nCreate (savedInstanceState );
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
251
s
etContentView(R
.l
ayout
.a
ctivity_main);
//initiate
an
autocompletetext
view
AutoCompleteTextView
simpleAutoCompleteTextView= (
AutoCompleteTextView )
findViewById(R
.
i
d
.simpleAutoCompleteTextView );
ArrayAdapter
adapter=n
ew
A
rrayAdapter (t
his,
android .R
.l
ayout.s
imple_list_item_1,
countryNameList);
s
impleAutoCompleteTextView .setAdapter
(a
dapter );
s
impleAutoCompleteTextView .setThreshold(1
);
//startsearching from
1
character
s
impleAutoCompleteTextView .setAdapter
(a
dapter );
/ /set the
adapterfordisplaying
countryname
list
}
}
Output:
NowstarttheAVDinEmulatorandruntheApp.Type‘i’&itwillshow‘India’assuggestion,
type‘A’&itwillshow‘Australia’assuggestionandsoon.Thisisdoneusing
AutoCompleteTextView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
252
ProgressBar
ProgressBarTutorialWithExampleInAndroidStudio
InAndroid,ProgressBarisusedtodisplaythestatusofworkbeingdonelikeanalyzingstatusof
workordownloadingafileetc.InAndroid,bydefaultaprogressbarwillbedisplayedasa
spinningwheelbutIfwewantittobedisplayedasahorizontalbarthenweneedtousestyle
attributeashorizontal.Itmainlyusethe“android.widget.ProgressBar”class.
ImportantNote:A
progressbarcanalsobemadeindeterminate.Inthismodeaprogressbar
showsacyclicanimationwithoutanindicationofprogress.Thismodeisusedinapplication
whenwedon’tknowtheamountofworktobedone.
Toaddaprogressbartoalayout(xml)file,youcanusethe<ProgressBar>element.Bydefault,a
progressbarisaspinningwheel(anindeterminateindicator).Tochangetoahorizontal
progressbar,applytheprogressbar’shorizontalstyle.
ProgressBarcode:
<ProgressBar
android:id
="
@+id/simpleProgressBar"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"/
>
HorizontalProgressBarcode:
<ProgressBar
android
:i
d
="
@+id/simpleProgressBar"
android
:l
ayout_width
="
fill_parent"
android
:l
ayout_height
="wrap_content"
style
="
@style/Widget.AppCompat.ProgressBar.Horizontal"
/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
253
ImportantMethodsUsedInProgressBar:
1.getMax()–returnsthemaximumvalueofprogressbar
Wecangetthemaximumvalueoftheprogressbarinjavaclass.Thismethodreturnsa
integervalue.BelowisthecodetogetthemaximumvaluefromaProgressbar.
ProgressBarsimpleProgressBar=(ProgressBar)findViewById(R.id.simpleProgressBar);
//initiatetheprogressbar
intmaxValue=simpleProgressBar.getMax();//getmaximumvalueoftheprogressbar
2.getProgress()–returnscurrentprogressvalue
Wecangetthecurrentprogressvaluefromaprogressbarinjavaclass.Thismethod
alsoreturnsaintegervalue.Belowisthecodetogetcurrentprogressvaluefroma
Progressbar.
ProgressBar
simpleProgressBar=(
ProgressBar
)f
indViewById(R
.i
d
.s
impleProgressBar
);
/
/initiate
theprogressbar
int
progressValue=s
impleProgressBar
.g
etProgress
();
/
/
get progress
value
from
theprogress
bar
AttributesofProgressBarInAndroid:
Nowlet’sdiscussimportantattributesthathelpsustoconfigureaProgressbarinxmlfile
(layout).
1.id:idisanattributeusedtouniquelyidentifyaProgressbar.
<ProgressBar
android:id="
@+id/simpleProgressBar"
android:layout_width ="fill_parent"
android:layout_height ="
wrap_content"
style
="
@style/W
idget
.A
ppCompat.P
rogressBar
.H
orizontal
"/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
254
2.max:m
axisanattributeusedinandroidtodefinemaximumvalueoftheprogresscantake.
Itmustbeanintegervaluelike100,200etc.
Belowweset100maximumvalueforaprogressbar.
<ProgressBar
android:id
="
@+id/simpleProgressBar"
android:layout_width
="fill_parent"
android:layout_height
="
wrap_content"
style
="
@style/W
idget
.A
ppCompat.P
rogressBar.H
orizontal
"
android:max
="100"
/
>
<!--set100maximum
value
for
theprogress
bar-->
SetMaxValueofProgressBarInJavaClass:
ProgressBar
simpleProgressBar=(ProgressBar
)
findViewById
(R
.i
d.s
impleProgressBar
);
/
/
initiate
theprogress
bar
simpleProgressBar.s
etMax
(1
00
);
/
/100
maximum
value
for
the progress
bar
3.progress:progressisanattributeusedinandroidtodefinethedefaultprogressvalue
between0andmax.Itmustbeanintegervalue.
Belowwesetthe100maxvalueandthenset50defaultprogress.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
255
<ProgressBar
android:id
="
@+id/simpleProgressBar"
android:layout_width
="fill_parent"
android:layout_height
="
wrap_content"
android:max
="100"
style
="
@style/W
idget
.A
ppCompat.P
rogressBar
.H
orizontal
"
android:progress
="
50"/>
<!--//
50
default
progress
value-->
SettingProgressValueofProgressBarInJavaClass:
ProgressBar
simpleProgressBar=(ProgressBar)f
indViewById
(R.
id
.s
impleProgressBar);
/
/initiate
the
progressbar
simpleProgressBar.s
etMax
(1
00
);
/
/100
maximumvalue
fortheprogressvalue
simpleProgressBar.s
etProgress
(5
0);
/
/
50
defaultprogress value
for
theprogressbar
4.progressDrawable:p
rogressdrawableisanattributeusedinAndroidtosetthecustom
drawablefortheprogressmode.
Belowwesetacustomgradientdrawablefortheprogressmodeofaprogressbar.Beforeyoutry
belowcodemakesuretodownloadaprogressiconfromthewebandaddinyourdrawable
folder.
Step1:A
ddthiscodeinactivity_main.xmlormain.xmlinsidelayout.
<ProgressBar
android:id="
@+id/simpleProgressBar"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:max="
100"
android:progress ="60"
android:layout_marginTop ="
100dp"
style
="
@style/W
idget.A
ppCompat.P
rogressBar
.H
orizontal
"
android:progressDrawable ="
@drawable/custom_progress"
/><!--custom
progress
drawable
for
progressmode-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
256
Step2:C
reateanewdrawableresourcexmlindrawablefolderandnameitcustom_progress.
Hereaddthebelowcodewhichcreatesgradienteffectinprogressbar.
<?
xml
version="1.0"
encoding
="
utf-8"
?>
<layer-listx
mlns:android ="
http://schemas.android.com/apk/res/android"
>
<item>
<shape>
<gradient
android:endColor
="
#fff"
android:startColor
="
#1f1"
android:useLevel
="
true"/>
</shape>
</item>
</layer-list>
5.background:backgroundattributeisusedtosetthebackgroundofaProgressbar.Wecan
setacolororadrawableinthebackgroundofaProgressbar.
BelowwesettheblackcolorforthebackgroundofaProgressbar.
<ProgressBar
android:id
="
@+id/simpleProgressBar"
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:max
="100"
android:progress
="
50"
style
="
@style/W
idget.AppCompat.P
rogressBar.H
orizontal
"
android:background
="
#000" />
<!--black
background
colorfor
progress
bar-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
257
6.indeterminate:i ndeterminateattributeisusedinAndroidtoenabletheindeterminate
mode.Inthismodeaprogressbarshowsacyclicanimationwithoutanindicationofprogress.
Thismodeisusedinapplicationwhenwedon’tknowtheamountofworktobedone.Inthis
modetheactualworkingwillnotbeshown.
Inbelowcodewesettheindeterminatetotrue.
<ProgressBar
android:id
="
@+id/simpleProgressBar"
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:max
="100"
android:progress
="50"
android:background
="
#000"
android:padding
="
20dp" style
="
@style
/W
idget
.A
ppCompat.P
rogressBar
.H
orizontal
"
android:indeterminate
="true"
/><!--true
valuefor
indeterminate-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
258
SettingindeterminateofProgressBarInJavaclass”
ProgressBar
simpleProgressBar=(
ProgressBar
)f
indViewById (R
.i
d
.s
impleProgressBar
);
/
/initiate
the
progressbar
simpleProgressBar.s
etBackgroundColor
(C
olor
.BLACK
);
/
/
black background
color
forthe
progress
bar
7.padding:paddingattributeisusedtosetthepaddingfromleft,right,toporbottomof
ProgressBar.
paddingRight:setthepaddingfromtherightsideoftheProgressbar.
paddingLeft:setthepaddingfromtheleftsideoftheProgressbar.
paddingTop:s etthepaddingfromthetopsideoftheProgressbar.
paddingBottom:setthepaddingfromthebottomsideoftheProgressbar.
Padding:s etthepaddingfromtheallside’softheProgressbar.
Belowwesetthe20dppaddingfromalltheside’softheProgressbar.
<ProgressBar
android:id
="
@+id/simpleProgressBar"
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:max
="100"
android:progress
="50"
android:background
="
#000"
style
="
@style/W
idget .AppCompat.P
rogressBar
.H
orizontal"
android:padding
="
20dp" /><!--//
20dp
paddingfrom
all
the
sides
of
the
progress
bar-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
259
ProgressBarExampleInAndroidStudio:
InthefirstexampleofProgressBarwedisplayedadefaultspinningwheelprogressbaranda
startbuttonwheneverauserclickonthebuttontheprogressbarisdisplayed.Belowisthefinal
output,downloadcodeandstepbystepexplanation:
Step1:CreateanewprojectandnameitProgressBarExample.
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
…t
hen
F
ill
the
formsa
nd
click"
Finish"
button.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
260
Step2:O
penres ->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthisstepweopenanxmlfileandaddthecodefordisplayingaprogressbar andsetits
visibilitytoinvisibleandonestartbutton.
<RelativeLayout
x
mlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
=".MainActivity" >
<ProgressBar
android:id
="@+id/simpleProgressBar"
android:layout_width
="wrap_content"
android:layout_height
="
wrap_content"
android:visibility
="invisible"
android:layout_centerHorizontal
="true"
/>
<Button
android:id
="@+id/startButton"
android:layout_width
="200dp"
android:layout_height
="
wrap_content"
android:text
="
Start"
android:textSize
="
20sp"
android:textStyle
="bold"
android:layout_centerHorizontal
="true"
android:layout_marginTop
="
100dp"
android:padding
="10dp"
android:background
="#0f0"
android:textColor
="#fff" />
</RelativeLayout>
Step3:NowOpensrc->package->MainActivity.java
InthisstepweopenMainActivitywhereweaddthecodetoinitiatetheprogressbar&button
andthenperformclickeventonbuttonwhichdisplaytheprogressbar.
package
example
.gb
.progressbarexample ;
import
android.g
raphics .C
olor;
import
android.s
upport .v
7.app
.A
ppCompatActivity
;
import
android.o
s.B
undle ;
import
android.v
iew .M
enu;
import
android.v
iew .M
enuItem ;
import
android.v
iew .V
iew;
import
android.w
idget .P
rogressBar ;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
261
import
android .w
idget .Button ;
publicc
lassMainActivity extends AppCompatActivity {
@Override
protected
voidonCreate (B
undle
savedInstanceState ){
super
.onCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .activity_main );
//
initiate progress bar andstart button
final
ProgressBar simpleProgressBar= (
ProgressBar )
findViewById (R.
i
d.s
impleProgressBar );
Button
startButton= (B
utton ) findViewById (R
.i
d
.s
tartButton );
//
perform click event onbutton
s
tartButton .s
etOnClickListener (n
ew V
iew.OnClickListener ()
{
@Override
public voidonClick (V
iew
v){
//
visible the progress bar
s
impleProgressBar .s
etVisibility (V
iew .V
ISIBLE );
}
});
}
}
Output:
NowstarttheAVDinEmulatorandruntheApp.ClickonthestartbuttonandProgressBarwill
bedisplayedonscreen.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
262
HorizontalProgressBarExampleInAndroidStudio:
Inthesecondexamplewedisplayahorizontalprogressbarwithdrawablebackgroundanda
startbutton.Herewheneverauserclicksonbuttonathreadisusedtostarttheprogress.Below
isthefinaloutput,downloadcodeandstepbystepexplanation:
Step1:CreateanewprojectandnameitProgressBarExample.
Select
F
ile
-
>
N
ew
-
>
N
ew
P
roject
…t
hen
F
ill
the
formsa
nd
click"
Finish"
button.
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthisstepweopenanxmlfileandaddthecodefordisplayingahorizontalprogressbarby
usingstyleproperty,drawableprogressxmlandonestartbutton.
<RelativeLayoutx
mlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:layout_width
="match_parent"
android:layout_height
="
match_parent"
android:background
="#000"
android:paddingBottom
="
@dimen/activity_vertical_margin"
android:paddingLeft
="
@dimen/activity_horizontal_margin"
android:paddingRight
="@dimen/activity_horizontal_margin"
android:paddingTop
="@dimen/activity_vertical_margin"
tools:context
="
.MainActivity" >
<ProgressBar
android:id
="
@+id/simpleProgressBar"
style
="
@
style /W
idget .A
ppCompat.P
rogressBar
.H
orizontal"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
263
ndroid:layout_width
a ="fill_parent"
android:layout_height
="
wrap_content"
android:layout_centerHorizontal
="true"
android:layout_marginTop
="
70dp"
android:max
="
100"
android:progress
="
0"
android:progressDrawable
="
@drawable/custom_progress"
/
>
<Button
android:id
="
@+id/startButton"
android:layout_width
="200dp"
android:layout_height
="
wrap_content"
android:layout_centerHorizontal
="
true"
android:layout_marginTop
="
120dp"
android:background
="#0f0"
android:padding
="
10dp"
android:text
="
Start"
android:textColor
="
#fff"
android:textSize
="20sp"
android:textStyle
="
bold" /
>
</RelativeLayout>
Inthisstepwecreateacustomdrawablexmlfortheprogressbar.Inthisxmlwecreatealayer
listinwhichwecreateanitemandthensetthegradientcolorsforourcustomprogressbar.
<?
xml
version="1.0"
encoding
="
utf-8"
?>
<layer-listx
mlns:android ="
http://schemas.android.com/apk/res/android"
>
<item>
<shape>
<gradient
android:endColor
="
#fff"
android:startColor
="
#1f1"
android:useLevel
="
true"/>
</shape>
</item>
</layer-list>
Step4:Open app->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodetoinitiatetheprogressbar,buttonandthen
performclickeventonbutton.Afterthatwestarttheprogressinginaprogressbarusinga
thread.
package
example
.gb
.p
rogressbarexample
;
import
android.a
pp.D
ialog
;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
264
import
android .c
ontent .D
ialogInterface ;
import
android .c
ontent .I
ntent ;
import
android .g
raphics .Color ;
import
android .p
rovider .Settings ;
import
android .s
upport .v
7.app.A
lertDialog ;
import
android .s
upport .v
7.app.A
ppCompatActivity ;
import
android .o
s.Bundle ;
import
android .v
iew .Menu ;
import
android .v
iew .MenuItem ;
import
android .v
iew .View ;
import
android .w
idget .ProgressBar ;
import
android .w
idget .Button ;
import
android .w
idget .Toast ;
publicc
lassMainActivity extends A
ppCompatActivity {
int
progress= 0;
ProgressBar
simpleProgressBar ;
@Override
protected
void
onCreate (Bundle
savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .activity_main );
//
initiate progress bar and start button
s
impleProgressBar= (P
rogressBar ) findViewById (R
.i
d
.s
impleProgressBar
);
Button
startButton= (
Button )findViewById (R.
id
.startButton
);
//
perform click event on button
s
tartButton .setOnClickListener (new V
iew.OnClickListener ()
{
@Override
public v
oid onClick (View
v){
//
call a
function
s
etProgressValue (p
rogress );
}
});
}
private
v
oid setProgressValue (final intprogress ){
//
set the progress
s
impleProgressBar .s
etProgress (p
rogress );
//
thread is used tochange the progress value
Thread
thread= newThread (newRunnable (){
@Override
public v
oid run(){
try
{
Thread .sleep (1
000 );
}c
atch (InterruptedException
e){
e
.p
rintStackTrace ();
}
s
etProgressValue (p
rogress+ 10
);
}
});
t
hread .s
tart ();
}
@Override
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
265
public
b
oolean
onCreateOptionsMenu (M
enu
menu){
//
Inflatethe
menu;
thisadds
items to
theactionbar
if
it
is
present.
g
etMenuInflater().
inflate
(R
.m
enu
.menu_main,menu
);
return
t
rue
;
}
Override
@
public
b
oolean
onOptionsItemSelected (M
enuItem
item){
//
Handle action
baritem
clickshere. Theactionbar
will
//
automatically handleclicksonthe
Home/Up button,so
long
//
as youspecify
a
parent activityinAndroidManifest.xml.
int
id =
item.g
etItemId();
/noinspection
/ SimplifiableIfStatement
if
(
i
d==
R.i
d
.a
ction_settings){
returnt
rue;
}
return
s
uper
.o
nOptionsItemSelected
(i
tem
);
}
}
Output:
NowruntheAppinAVD,clickonstartbuttonandyouwillseehorizontalprogressbar.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
266
TimePicker
InAndroid,TimePickerisawidgetusedforselectingthetimeofthedayineitherAM/PMmode
or24hoursmode.Thedisplayedtimeconsistofhours,minutesandclockformat. Ifweneedto
showthisviewasaDialogthenwehavetouseaTimePickerDialogclass.
TimePickercode:
<TimePicker
android:id
="
@+id/simpleTimePicker"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:timePickerMode="
spinner"
/>
MethodsofTimePicker:
Let’sdiscusssomecommonmethodsofatimepicker,whichareusedtoconfigurea
timepickerinourapplication.
1.setCurrentHour(IntegercurrentHour):
Thismethodisusedtosetthecurrenthoursinatimepicker.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
267
setHour(Integerhour):setCurrentHour()methodwasdeprecatedinAPIlevel23.Fromapi
level23wehavetousesetHour(Integerhour).Inthismethodthereisonlyoneparameterof
integertypewhichisusedtosetthevalueforhours.
Belowwesetthe5valueforthecurrenthours.
TimePicker
simpleTimePicker =(TimePicker)findViewById(R
.i
d.s
impleTimePicker
);
/
/
initiate
a
time
picker
//
set
thevalue
for
current hours
simpleTimePicker.s
etCurrentHour (5
);
/
/
beforeapilevel 23
simpleTimePicker.s
etHour
(5
);
/
/fromapilevel
23
2.setCurrentMinute(IntegercurrentMinute):
Thismethodisusedtosetthecurrentminutesinatimepicker.
setMinute(Integerminute):setCurrentMinute()m
ethodwasdeprecatedinAPIlevel23.
Fromapilevel23wehavetousesetMinute(Integerminute).Inthismethodthereisonlyone
parameterofintegertypewhichsetthevalueforminutes.
Belowwesetthe35valueforthecurrentminutes.
TimePicker
simpleTimePicker=(
TimePicker)findViewById
(R.
id
.s
impleTimePicker
);
/
/
initiate
a
time
picker
//
set
thevalue
for
current
hours
simpleTimePicker.s
etCurrentMinute(3
5
);
/
/before
apilevel 23
simpleTimePicker.s
etMinute
(3
5
);
/
/from
apilevel
23
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
268
3.getCurrentHour():
Thismethodisusedtogetthecurrenthoursfromatimepicker.
getCurrentHour():g
etCurrentHour()methodwasdeprecatedinAPIlevel23.Fromapilevel
23youhavetousegetHour().Thismethodreturns anintegervalue.
Belowwegetthevalueofhoursfromatimepickersetbyuser.
TimePicker
simpleTimePicker=(
TimePicker
)f
indViewById
(R.
id
.s
impleTimePicker);
/
/
initiate
a
time
pickerint
hours=s
impleTimePicker .g
etCurrentHour
();
/
/before api
level
23
int
hours=
simpleTimePicker
.g
etHour ();
/
/
after
api
level 23
4.getCurrentMinute():
Thismethodisusedtogetthecurrentminutesfromatimepicker.
getMinute():getCurrentMinute()m
ethodwasdeprecatedinAPIlevel23.Fromapilevel23
wehavetousegetMinute().Thismethodreturns anintegervalue.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
269
Belowwegetthevalueofminutesfromatimepicker.
TimePicker
simpleTimePicker=(
TimePicker
)f
indViewById (R
.i
d
.s
impleTimePicker);
/
/
initiate
a
timepicker
int
minutes=
simpleTimePicker
.getCurrentMinute();
/
/before api
level
23
int
minutes=
simpleTimePicker
.getMinute
();/
/
after
api level23
5.setIs24HourView(Booleanis24HourView):
ThismethodisusedtosetthemodeoftheTimepickereither24hourmodeorAM/PMmode.In
thismethodwesetaBooleanvalueeithertrueorfalse.Truevalueindicate24hourmodeand
falsevalueindicateAM/PMmode.
Belowwesetthecurrentmodeofthetimepicker.
TimePicker
simpleTimePicker=
(
TimePicker
)f
indViewById(R
.i
d
.s
impleTimePicker);
/
/initiate
a
time
picker
simpleTimePicker
.s
etIs24HourView(t
rue
);
/
/set
24
hoursmodefor
the
time
picker
6.is24HourView():
Thismethodisusedtocheckthecurrentmodeofthetimepicker.Thismethodreturnstrueif
its24hourmodeorfalseifAM/PMmodeisset.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
270
Belowwegetthecurrentmodeofthetimepicker:
TimePicker
simpleTimePicker=
(
TimePicker
)f
indViewById(R
.i
d
.s
impleTimePicker
);
/
/initiate
a
time
picker
Boolean
mode
=s
impleTimePicker
.i
s24HourView ();
/
/
check
thecurrent
mode
of
thetime
picker
7.setOnTimeChangedListener(TimePicker.OnTimeChangedListener
onTimeChangedListener):
Thismethodisusedtosetthecallbackthatindicatesthetimehasbeenadjustedbytheuser.
onTimeChanged(TimePickerview,inthourOfDay,intminute)isanoverridefunctionofthis
listenerinwhichwehavethreeparametersfirstisforTimePicker,secondforgettinghourofthe
dayandlastisforgettingtheminutesafterchangingthetimeofthetimepicker.
Belowweshowtheuseofontimechangedlistenerofatimepicker.
TimePicker
simpleTimePicker=(
TimePicker
)f
indViewById(R
.i
d
.s
impleTimePicker
);
/
/initiate
a
timepicker
simpleTimePicker .s
etOnTimeChangedListener(new
T
imePicker.O
nTimeChangedListener
(){
@Override
publicv
oidonTimeChanged
(T
imePicker
view
,int
hourOfDay
,int
minute
){
}
});
AttributesofTimePicker:
Nowlet’s wediscussabouttheattributesthathelpsustoconfigureatimepickerinyourxml
file(layout).
1.id:idisanattributeusedtouniquelyidentifyatimepicker.
<TimePicker
android:id="@+id/simpleTimePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/><!--idofatimepicker-->
2.timePickerMode:timepickermodeisanattributeoftimepickerusedtosetthemode
eitherspinnerorclock.Defaultmodeisclockbutthismodeisnolongerusedafterapilevel21,
sofromapilevel21youhavetosetthemodetospinner.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
271
Belowwesetthemodetospinner.
<TimePicker
android:id
="
@+id/simpleTimePicker"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:timePickerMode="
spinner"
/
><
!--
time
picker
mode
of
a
time
picker
-->
3.background:backgroundattributeisusedtosetthebackgroundofatimepicker.Wecan
setacolororadrawableimageinthebackground.Wecanalsosetthebackgroundcolor
programmaticallymeansinjavaclass.
Belowwesettheorangecolorforthebackgroundofatimepicker.
<TimePicker
android:id
="
@+id/simpleTimePicker"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:timePickerMode
="spinner"
android:background
="
#F88F00" /
>
<
!-- orange
background
color
for
the
time
picker
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
272
SettingTimePickerBackgroundInJavaClass:
TimePicker
simpleTimePicker=(
TimePicker
)f
indViewById (R
.i
d
.s
impleTimePicker
);
/
/initiate
a
time
picker
simpleTimePicker.s
etBackgroundColor
(C
olor.Y
ELLOW
);
/
/Yellow background
colorfor
the
backgroundof
a
time
picker
4.padding:paddingattributeisusedtosetthepaddingfromleft,right,toporbottomfora
timepicker.
paddingRight:s etthepaddingfromtherightsideofthetimepicker.
paddingLeft:setthepaddingfromtheleftsideofthetimepicker.
paddingTop:s etthepaddingfromthetopsideofthetimepicker.
paddingBottom:s etthepaddingfromthebottomsideofthetimepicker.
Padding:setthepaddingfromtheallside’softhetimepicker.
Belowexamplewesetthe20dppaddingfromalltheside’softhetimepicker.
<TimePicker
android:id
="
@+id/simpleTimePicker"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:timePickerMode="
spinner"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
273
android:layout_centerHorizontal="true"
android:layout_marginTop
="50dp"
android:padding
="
20dp"
/>
<
!--20dppadding
from
all
the
sides
of
a
time
picker
-->
ExampleofTimePickerinAndroidStudio:
Example1:Inthebelowexampleoftimepickerwewillshowyoutheuseoftimepickerinour
application.Forthatwedisplaysimpletimepickerandatextviewinourxmlfileandperform
setOnTimeChangedListener()event,sothatwheneverauseradjustthetimethecurrent
displayedtimeoftimepickerisdisplayedbyusingaToastandalsodisplayedinthetextview.
Belowisthefinaloutput,downloadprojectcodeandstepbystepexplanation:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
274
Step1:C
reateanewprojectandnameitTimePickerExample
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthisstepweopenanxmlfileandaddthecodefordisplayingatimepickerwithspinnermode
andtextviewfordisplayingtimeoftimepicker.
<RelativeLayout
xmlns:android ="
http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
=".MainActivity" >
<TimePicker
android:id
="@+id/simpleTimePicker"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_centerHorizontal
="true"
android:layout_marginTop
="
50dp"
android:background
="#090"
android:padding
="20dp"
android:timePickerMode
="spinner"/>
<TextView
android:id
="@+id/time"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_centerHorizontal
="true"
android:text
="
Time Is
::"
android:textColor
="#090"
android:textSize
="
20sp"
android:textStyle
="bold" /
>
</RelativeLayout>
Step3:Open app->package->MainActivity.java
InthisstepweopenMainActivitywhereweaddthecodetoinitiatethetimepickerandatext
viewtodisplaytimeoftimepickerandthenweperformsetOnTimeChangedListener()eventso
wheneverauseradjustthetimethecurrentdisplayedtimeoftimepickerisdisplayedbyusinga
Toastandalsodisplayedinthetextview.
package
example
.gb
.t
imepickerexample
;
import
android.a
pp.T
imePickerDialog
;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
275
import
android .g
raphics .C
olor ;
import
android .s
upport .v7.a
pp .A
ppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .Menu;
import
android .v
iew .MenuItem ;
import
android .v
iew .View;
import
android .w
idget .T
extView ;
import
android .w
idget .T
imePicker ;
import
android .w
idget .T
oast ;
import
org.w
3c .d
om.Text ;
import
java.u
til .C
alendar ;
publicc
lassMainActivity e
xtends A
ppCompatActivity {
TextView
time;
TimePicker
simpleTimePicker ;
@Override
protected
void
onCreate (Bundle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .a
ctivity_main );
// i
nitiate the view's
t
ime= (
TextView )findViewById (R.
id
.t
ime);
s
impleTimePicker= (TimePicker )findViewById (R.
id
.simpleTimePicker );
s
impleTimePicker .setIs24HourView (false);/
/used todisplay AM/PM mode
//
perform set ontime changed listener event
s
impleTimePicker .setOnTimeChangedListener (newT
imePicker .O
nTimeChangedListener ()
{
@Override
public v
oid
onTimeChanged (T
imePicker
view ,int
hourOfDay ,int
minute ){
//
display a
toast withchanged values oftimepicker
Toast
.makeText (g
etApplicationContext (),
hourOfDay+ "
"+
minute,
Toast
.LENGTH_SHORT ).
show ();
t
ime .s
etText ("
Time is
:: "+
hourOfDay+ "
:"+
minute );
/
/setthe current
timeintext view
}
});
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
276
Output:
NowruntheAppinAVDandyouwillseeTimePickeronthescreen.Changethetimeanditwill
bedisplayedasToastandalsoinTextView.
ExampleofTimePickerDialoginAndroidStudio:
Example2:InthesecondexampleofTimePickerwewillshowtheuseoftimepickerdialogin
ourapplication.Todothatwewilldisplayedittextinourxmlfileandperformaclicklistener
eventonit,sowheneverauserclickonittimepickerdialogwillappearandfromthereusercan
adjustthetimeandafterselectingthetimeitwillbedisplayedintheedittext.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
277
Step1:C
reateanewprojectandnameitTimePickerExample
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthisstepweopenanxmlfileandaddthecodefordisplayingaedittexttodisplaytimeoftime
picker.
<RelativeLayout
x
mlns:android ="
http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
="
.MainActivity" >
<EditText
android:id
="
@+id/time"
android:layout_width
="
200dp"
android:layout_height
="wrap_content"
android:layout_centerHorizontal
="true"
android:hint
="
Select Time..."
android:textColor
="#090"
android:textColorHint
="#090"
android:background
="#d4d4d4"
android:padding
="15dp"
android:textSize
="
20sp"
android:textStyle
="bold" /
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
278
</RelativeLayout>
Step3:O
pensrc->package->MainAcivity.java
InthisstepweopenMainActivitywhereweaddthecodetoinitiatetheedittexttodisplaytime
oftimepickerandperformclickeventonedittext,sowheneverauserclicksonedittextatime
pickerdialogwillappearfromthereusercansetthetime.Andfinallythenthetimewillbe
displayedintheedittext.
package
example .gb.t
imepickerexample ;
import
android .a
pp .T
imePickerDialog ;
import
android .g
raphics .Color ;
import
android .s
upport .v
7.a
pp .A
ppCompatActivity ;
import
android .o
s.Bundle ;
import
android .v
iew .Menu ;
import
android .v
iew .MenuItem ;
import
android .v
iew .View ;
import
android .w
idget .EditText ;
import
android .w
idget .TextView ;
import
android .w
idget .TimePicker ;
import
android .w
idget .Toast ;
import
org.w
3c .d
om .T
ext ;
import
java.u
til .C
alendar ;
public
c
lassMainActivity extends A
ppCompatActivity {
EditText
time;
@Override
protected
void
onCreate (Bundle savedInstanceState ){
super
.onCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .a
ctivity_main );
// i
nitiate the edit text
t
ime= (
EditText )findViewById (R.
id
.time
);
//
perform click event listener on edittext
t
ime.setOnClickListener (n
ew V
iew .OnClickListener (){
@Override
public v
oid onClick (V
iew v)
{
Calendar
mcurrentTime= C
alendar .g
etInstance ();
int
hour= mcurrentTime .g
et(Calendar .HOUR_OF_DAY );
int
minute= mcurrentTime .g
et(C
alendar .M
INUTE );
TimePickerDialog
mTimePicker ;
m
TimePicker =n
ew T
imePickerDialog (MainActivity .this
,n
ew
TimePickerDialog .OnTimeSetListener (){
@Override
public void
onTimeSet (TimePicker timePicker,i
nt
selectedHour
,
int
selectedMinute ){
t
ime .setText (s
electedHour+ "
:"+
selectedMinute
);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
279
}
,
}
hour ,
minute
,t
rue);
//Yes
24
hour
time
m
TimePicker .s
etTitle("
Select
Time"
);
m
TimePicker .s
how
();
}
});
}
}
Output:
NowruntheAppinAVDandyouwillseeedittextaskingusertoselecttime.Whenuserclickon
it,timepickerdialogwillopenfromthereusercanselecttime.Andthenthistimewillbe
displayedinEditText.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
280
CalendarView
InAndroid,CalendarViewwidgetwasaddedinAPIlevel11(Androidversion3.0)whichmeans
thisviewisonlysupportedinthedevicethatarerunningonAndroid3.0andhigherversion.It
isusedfordisplayingandselectingdates.
Thesupportedrangeofdatesofthiscalendarisconfigurable.Usercanselectadateby
taping/clickingonitandalsocanscroll&findthecalendartoadesireddate.Developercan
alsosetminimumandmaximumdateshownincalendarview.
BasicCalendarViewXMLCode:
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
281
ImportantMethodsOfCalendarView:
Let’swediscusssomeimportantmethodsofCalendarViewthatmaybecalledinorderto
managetheCalendarView.
1.getDate():T
hismethodisusedtogettheselecteddateofCalendarViewinmilliseconds
sinceJanuary1,197000:00:00inuser’spreferred timezone.Thismethodreturnslongtype
valueforselecteddate.
BelowwegettheselectedofCalendarViewinmilliseconds.
CalendarView
simpleCalendarView=(C
alendarView)
findViewById
(R
.i
d
.s
impleCalendarView
);/
/
get
the
referenceofCalendarView
long
selectedDate=
simpleCalendarView .g
etDate
();/
/
get
selecteddate
in
milliseconds
2.setDate(longdate):Thismethodisusedtosettheselecteddateinmillisecondssince
January1,197000:00:00inuser’spreferred timezone.
BelowwesettheselecteddateinmillisecondsforaCalendarView.
CalendarView
simpleCalendarView=
(C
alendarView
)
findViewById(R
.i
d
.s
impleCalendarView
);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etDate
(1
463918226920L);
/
/
set
selected
date 22
May
2016
in
milliseconds
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
282
3.setFirstDayOfWeek(intfirstDayOfWeek):Thismethodisusedtosetthefirstdayofthe
week.
Belowwesetthe2valuemeansMondayasthefirstdayoftheweek.
CalendarView
simpleCalendarView=
(C
alendarView)findViewById
(R
.i
d
.s
impleCalendarView);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etFirstDayOfWeek(2
);
/
/
set
Mondayas
the
first day
of
the
week
4.getFirstDayOfWeek():T
hismethodisusedtogetthefirstdayofweek.Thismethod
returnsaninttypevalue.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
283
BelowwegetthefirstdayoftheweekofCalendarView.
CalendarView
simpleCalendarView=(C
alendarView
)
findViewById(R
.i
d
.s
impleCalendarView);
/
/
getthe
reference
ofCalendarView
int
firstDayOfWeek=
simpleCalendarView .g
etFirstDayOfWeek
();
/
/getfirst
day
of
the
week
5.setMaxDate(longmaxDate):Thismethodisusedtosetthemaximaldatesupportedby
thisCalendarViewinmillisecondssinceJanuary1,197000:00:00inuser’spreferredtimezone.
BelowwesetthelongvalueformaximaldatesupportedbytheCalendarView.
CalendarView
simpleCalendarView=(C
alendarView)
findViewById
(R
.i
d
.s
impleCalendarView);
/
/
get
the
reference of
CalendarView
simpleCalendarView.setMaxDate
(1
463918226920L);
/
/set
22nd
May
2016 as
max
date
supported
by
this
CalendarView
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
284
6.getMaxDate():Thismethodisusedtogetthemaximaldatesupportedbythis
CalendarViewinmillisecondssinceJanuary1,197000:00:00inuser’spreferredtimezone.This
methodreturnslongtypevalueformaximaldatesupportedbythisCalendarView.
Belowwefirstlysetthelongvalueforthemaximaldateandthengetthemaximalvalue
supportedbytheCalendarView.
CalendarView
simpleCalendarView=
(C
alendarView)
findViewById(R
.i
d
.s
impleCalendarView
);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etMaxDate
(1
463918226920L);
/
/set
max
datesupportedby
this
CalendarViewlongmaxDate=
simpleCalendarView.getMaxDate(); //
getmax
date
supported
bythis
CalendarView
7.setMinDate(longminDate):Thismethodisusedtotosettheminimaldatesupportedby
thisCalendarViewinmillisecondssinceJanuary1,197000:00:00inuser’spreferredtimezone.
BelowwesetthelongvalueforminimaldatesupportedbytheCalendarView.
CalendarView
simpleCalendarView=
(C
alendarView)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etMinDate
(1
463918226920L);
/
/set
min
date
supportedby
this
CalendarView
8.getMinDate():Thismethodisusedtotogettheminimaldatesupportedby
thisCalendarViewinmillisecondssinceJanuary1,197000:00:00inuser’spreferredtimezone.
ThismethodreturnslongtypevalueforminimaldatesupportedbythisCalendarView.
Belowwefirstlysetthelongvaluefortheminimaldateandthengettheminimalvalue
supportedbytheCalendarView.
CalendarView
simpleCalendarView=
(C
alendarView)
findViewById(R
.i
d
.s
impleCalendarView
);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etMinDate
(1
463918226920L);
/
/set
min
datesupportedby
this
CalendarViewlongminDate=
simpleCalendarView.getMinDate(); //
getmin
date
supported
bythis
CalendarView
9.setShowWeekNumber(booleanshowWeekNumber):Thismethodisusedtoshowor
hidetheweeknumberofCalendarView.InthismethodwesetBooleantypevaluemeanstrueor
false.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
285
BelowwesetthetruevalueforshowingtheweeknumbersofCalendarView.
CalendarView
simpleCalendarView=
(C
alendarView
)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etShowWeekNumber(t
rue
);
/
/
set
true
value
forshowing
the
week
numbers.
10.getShowWeekNumber():T
hismethodisusedtocheckwhethertheweeknumberare
shownornot.ThismethodreturnsBooleantypevaluemeanstrueorfalse.Trueindicatesweek
numbersareshownandfalseindicatesweeknumbersarecurrentlyhidden.
Belowwecheckswhethertheweeknumberarecurrentlyshowingornot.
CalendarView
simpleCalendarView=
(C
alendarView
)
findViewById
(R
.i
d
.s
impleCalendarView);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.g
etShowWeekNumber();
/
/
checks
whether
the
week number
are
shown
or
not.
11.getSelectedDateVerticalBar():Thismethodisusedtogetthedrawablei.eusedforthe
verticalbarshownatthebeginningandattheendoftheselecteddate.Thismethodwas
deprecatedinAPIlevel23sonolongerusedbyMaterialstyleCalendarView.
Belowwegettheapplieddrawablefortheverticalbarshownatthebeginningandattheendof
theselecteddate.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
286
CalendarView
simpleCalendarView=
(C
alendarView
)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
get
the
referenceof
CalendarView
Drawable
verticalBar=s
impleCalendarView.g
etSelectedDateVerticalBar();
/
/
get
the
applied
drawable
for
thevertical
bar
12.setSelectedDateVerticalBar(Drawabledrawable):Thismethodisusedtosetthe
drawablefortheverticalbarshownatthebeginningandattheendoftheselecteddate.This
methodwasdeprecatedinAPIlevel23sonolongerusedbyMaterialstyleCalendarView.
Belowwesetthedrawablefortheverticalbarshownatthebeginningandattheendofthe
selecteddate.
CalendarView
simpleCalendarView= (C
alendarView )
findViewById
(R.
id
.s
impleCalendarView );
/
/
getthereference
ofCalendarView
simpleCalendarView .setSelectedDateVerticalBar (g
etResources().
getDrawable (R
.d
rawable
.i
c_launc
her
));/
/set
the
drawablefor
the vertical
bar
13.setSelectedDateVerticalBar(intresourceId):T
hismethodisusedtosetthecolorfor
theverticalbarshownatthebeginningandattheendoftheselecteddate.Thismethodwas
deprecatedinAPIlevel23sonolongerusedbyMaterialstyleCalendarView.
Belowwesetthebluecolorfortheverticalbarshownatthebeginningandattheendofthe
selecteddate.
CalendarView
simpleCalendarView=
(C
alendarView)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etSelectedDateVerticalBar(C
olor.B
LUE
);
/
/
setthe
color
for
the
vertical
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
287
bar
14.setSelectedWeekBackgroundColor(intcolor):Thismethodisusedtosetthecolorin
thebackgroundofselectedweekofCalendarView.ThismethodwasdeprecatedinAPIlevel23
sonolongerusedbyMaterialstyleCalendarView.
BelowwesettheblackcolorinthebackgroundofselectedweekofCalendarView.
CalendarView
simpleCalendarView=
(C
alendarView
)
findViewById
(R.
id
.s
impleCalendarView
);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etSelectedWeekBackgroundColor(C
olor
.B
LACK
);/
/set
black
color
in
the
background
ofselected
week
15.getSelectedWeekBackgroundColor():Thismethodisusedtogetthebackgroundcolor
ofselectedweekofCalendarView.Thismethodreturnsaninttypevalue.Thismethodwas
deprecatedinAPIlevel23sonolongerusedbyMaterialstyleCalendarView.
BelowwegettheappliedcolorinthebackgroundofselectedweekofCalendarView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
288
CalendarView
simpleCalendarView= (C
alendarView
)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
getthe
referenceof
CalendarView
int
backColor=s
impleCalendarView.getSelectedWeekBackgroundColor();/
/
get
applied
color
in
thebackgroundof
selected
week
16.getWeekNumberColor():T
hismethodisusedtogetthecolorofweeknumbers.This
methodreturnsaninttypevalue.ThismethodwasdeprecatedinAPIlevel23sonolongerused
byMaterialstyleCalendarView.
Belowwegettheappliedcolorofweeknumbers.
CalendarView
simpleCalendarView=(C
alendarView
)
findViewById(R
.i
d
.s
impleCalendarView
);
/
/
getthe
reference
ofCalendarView
int
weekNumberColor=s
impleCalendarView .g
etWeekNumberColor
();
/
/ get
applied
color
of
week
number
17.setWeekNumberColor(intcolor):T
hismethodisusedtosetthecolorfortheweek
numbers.ThismethodwasdeprecatedinAPIlevel23sonolongerusedbyMaterialstyle
CalendarView.
Belowwesettheredcolorofweeknumbers.
CalendarView
simpleCalendarView=
(C
alendarView
)
findViewById
(R.
id
.s
impleCalendarView
);/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etWeekNumberColor(C
olor
.R
ED
);
/
/
set
red
color for
the
week
number
18.setWeekSeparatorLineColor(intcolor):Thismethodisusedtosetthecolorforthe
weekseparatorline.ThismethodwasdeprecatedinAPIlevel23sonolongerusedbyMaterial
styleCalendarView.
Belowwesetthegreencolorfortheweekseparatorline.
CalendarView
simpleCalendarView=
(C
alendarView
)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
get
the
referenceof
CalendarView
simpleCalendarView.s
etWeekSeparatorLineColor(C
olor
.G
REEN
);
/
/
setgreen
color
for
the
week
separator
line.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
289
19.getWeekSeparatorLineColor():Thismethodisusedtogetthecolorofweekseparator
line.Thismethodreturnsaninttypevalue.ThismethodwasdeprecatedinAPIlevel23sono
longerusedbyMaterialstyleCalendarView.
Belowwegettheappliedcolorofweekseparatorline.
CalendarView
simpleCalendarView=
(C
alendarView)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
getthe
reference
of
CalendarView
int
weekSeperatorLineColor=s
impleCalendarView.g
etWeekSeparatorLineColor ();
/
/
get
applied
colorof
week
seperator
line
20.setUnfocusedMonthDateColor(intcolor):Thismethodisusedtosetthecolorforthe
datesofanunfocusedmonth.ThismethodwasdeprecatedinAPIlevel23sonolongerusedby
MaterialstyleCalendarView.
Belowwesetthegraycolorforthedatesofanunfocusedmonth.
CalendarView
simpleCalendarView=
(C
alendarView)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
getthe
reference
of
CalendarView
simpleCalendarView.s
etUnfocusedMonthDateColor(C
olor.G
RAY
);
/
/
setgray
color
for
the
dates
of
anunfocused
month
21.getUnfocusedMonthDateColor():T
hismethodisusedtogetthecolorforthedatesof
anunfocusedmonth.Thismethodreturnsinttypevalue.ThismethodwasdeprecatedinAPI
level23sonolongerusedbyMaterialstyleCalendarView.
Belowwegettheappliedcolorforthedatesofanunfocusedmonth.
CalendarView
simpleCalendarView=(C
alendarView
)
findViewById
(R
.i
d
.s
impleCalendarView
);
//
getthe
reference
ofCalendarView
int
unfocusedMonthDateColor =s
impleCalendarView.g
etUnfocusedMonthDateColor();
/
/
get
the
colorfor
the
dates
ofan
unfocused month
22.setFocusedMonthDateColor(intcolor):Thismethodisusedtosetthecolorforthe
datesofanfocusedmonth.ThismethodwasdeprecatedinAPIlevel23sonolongerusedby
MaterialstyleCalendarView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
290
Belowwesettheyellowcolorforthedatesofanfocusedmonth.
CalendarView
simpleCalendarView=
(C
alendarView
)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
getthe
reference
of
CalendarView
simpleCalendarView.s
etFocusedMonthDateColor(C
olor
.Y
ELLOW
);
/
/
setyellow
color
for
the
dates
of
focusedmonth
23.getFocusedMonthDateColor():T
hismethodisusedtogetthecolorforthedatesofan
focusedmonth.Thismethodreturnsinttypevalue.ThismethodwasdeprecatedinAPIlevel23
sonolongerusedbyMaterialstyleCalendarView.
Belowwegettheappliedcolorforthedatesofanfocusedmonth.
CalendarView
simpleCalendarView=
(C
alendarView
)
findViewById
(R
.i
d
.s
impleCalendarView
);
/
/
getthe
reference
of
CalendarView
int
focusedMonthDateColor=s
impleCalendarView.g
etFocusedMonthDateColor();
/
/
get
the
color
forthe
dates
of
focused
month
24.setOnDateChangeListener(OnDateChangeListenerlistener):T
hismethodisused
tosetthelistenertobenotifieduponselecteddatechange.
BelowweshowhowtousesetOnDateChangeListenereventofCalendarView.
CalendarView simpleCalendarView=
( C
alendarView)
findViewById(R
.i
d.s
impleCalendarView);
/
/
getthereferenceof
CalendarView
//
perform setOnDateChangeListener event
onCalendarView
simpleCalendarView .s
etOnDateChangeListener (n
ewC
alendarView
.O
nDateChangeListener ()
{
@Override
publicv
oid
onSelectedDayChange(C
alendarView
view
,i
nt
year
,int
month,i
nt
dayOfMonth){
//
addcodehere
}
});
AttributesofCalendarView:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
291
Nowlet’swediscusssomecommonattributesofaCalendarViewthathelpsustoconfigureitin
ourlayout(xml).
1.id:idattributeisusedtouniquelyidentifyaCalendarView.
BelowwesettheidoftheCalendarViewthatisusedtouniquelyidentifyit.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"/
>
<
!-- i
d
of
the
CalendarView
that
is
used
to
uniquely
identify
it-->
2.firstDayOfWeek:ThisattributesisusedtosetthefirstdayofweekaccordingtoCalendar.
WecanalsosetthisprogrammaticallymeansinjavaclassusingsetFirstDayOfWeek(int
firstDayOfWeek)method
Belowwesetthe2valuemeansMondayasthefirstdayoftheweek.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
android:firstDayOfWeek="
2"
/
>
<!--
set
the
2
value
means Monday
asthe
first
day
of
the
week
-->
3.focusedMonthDateColor:Thisattributeisusedtosetthecolorforthedatesofthe
focusedmonth.Wecanalsosetthisprogrammaticallymeansinjavaclassusing
setFocusedMonthDateColor(intcolor)method.
Belowwesettheyellowcolorforthedatesofanfocusedmonth.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
android:firstDayOfWeek="
2"
android:focusedMonthDateColor="
#ff0"/
>
<!--
set
the
yellow
colorfor
the
dates of
focused
month
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
292
4.unfocusedMonthDateColor:Thisattributeisusedtosetthecolorforthedatesofthe
unfocusedmonth.Wecanalsosetthisprogrammaticallymeansinjavaclassusing
setUnfocusedMonthDateColor(intcolor)method.
BelowwesettheRedcolorforthedatesofanfocusedmonth.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
android:firstDayOfWeek="
2"
android:unfocusedMonthDateColor="
#f00"
/
>
<!--
set
the
yellow
colorfor
the
datesof
an
unfocused
month
-->
5.maxDate:T
hisattributeisusedtosetthemaximaldatesupportedbythisCalendarView.
Thisattributeusemm/dd/yyyyformat.Wecanalsosetthisprogrammaticallymeansinjava
classusingsetMaxDate(longmaxDate)
Belowwesetthe05/22/2017asmaximaldatesupportedbytheCalendarView.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width="
fill_parent"
android:layout_height="fill_parent"
android:firstDayOfWeek="2"
android:maxDate
="
05/22/2017" /
>
<!--
set
maximaldatesupportedbythis
CalendarView
-->
6.minDate:ThisattributeisusedtosettheminimaldatesupportedbythisCalendarView.
Thisattributeusemm/dd/yyyyformat.Wecanalsosetthisprogrammaticallymeansinjava
classusingsetMinDate(longminDate)
Belowwesetthe05/22/2016asminimaldatesupportedbytheCalendarView.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width="
fill_parent"
android:layout_height="fill_parent"
android:firstDayOfWeek="2"
android:minDate
="
05/22/2016" /
>
<!--
set
minimaldatesupportedbythis
CalendarView
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
293
7.selectedDateVerticalBar:T
hisattributeisusedtosetthedrawable/colorforthevertical
barshownatthebeginningandattheendoftheselecteddate.Wecanalsosetthis
programmaticallymeansinjavaclassusingsetSelectedDateVerticalBar(intresourceId)or
setSelectedDateVerticalBar(Drawabledrawable)method.
Belowwesettheblackcolorfortheverticalbarshownatthebeginningandattheendofthe
selecteddate.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width="
fill_parent"
android:layout_height="fill_parent"
android:firstDayOfWeek="2"
android:selectedDateVerticalBar ="
@color/black"
/
>
<!--
set
blackcolor
forthe
vertical
bar
shownat
the
beginning
and
at
the
end
of
the
selected
date-->
8.selectedWeekBackgroundColor:T
hisattributeisusedtosetthecolorinthebackground
ofselectedweekofCalendarView.Wecanalsosetthisprogrammaticallyinjavaclassusing
setSelectedWeekBackgroundColor(intcolor)method.
BelowwesettheredcolorinthebackgroundofselectedweekofCalendarView.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
android:firstDayOfWeek="
2"
android:selectedWeekBackgroundColor="#f00"
/
>
<!--
set
red
in
the
backgroundof
selected week
of
CalendarView
-->
9.showWeekNumber:Thisattributeisusedtoshoworhidetheweeknumberof
CalendarView.InthismethodwesetBooleantypevaluemeanstrueorfalse.Wecanalsoset
thisprogrammaticallymeansinjavaclassusingsetShowWeekNumber(boolean
showWeekNumber)method.
BelowwesetthefalsevalueforhidingtheweeknumbersofCalendarView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
294
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width="
fill_parent"
android:layout_height="fill_parent"
android:firstDayOfWeek="2"
android:showWeekNumber="false"
/
>
<!--
set
the
false
value for
hiding the
week
numbers
of
CalendarView.
-->
10.weekNumberColor:Thisattributeisusedtosetthecolorfortheweeknumbers.
Belowwesettheredcolorofweeknumbers.Wecanalsosetthisprogrammaticallymeansin
javaclassusingsetWeekNumberColor(intcolor)method.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width="
fill_parent"
android:layout_height="fill_parent"
android:firstDayOfWeek="2"
android:weekNumberColor ="
#f00"/
>
<!--
set
red
color
for theweeknumbers
of
CalendarView.
-->
11.weekSeparatorLineColor:Thisattributeisusedtosetthecolorfortheweekseparator
line.Wecanalsosetthisprogrammaticallymeansinjavaclassusing
setWeekSeparatorLineColor(intcolor)method.
Belowwesetthegreencolorfortheweekseparatorline.
<CalendarView
android:id
="
@+id/simpleCalendarView"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
android:firstDayOfWeek="
2"
android:weekSeparatorLineColor="
#0f0"/
>
<!--
set
green
color
forthe
week
seperator
line
-->
CalendarViewExampleInAndroidStudio:
BelowistheexampleofCalendarViewinwhichwedisplayaCalendarViewforaminimaland
maximalsupporteddate.Inthisweset01/01/2016minimaland01/01/2018asmaximaldatefor
thiscalendarView.Wesetfocusedandunfocusedmonthdatecolorandalsousedsomeother
functionsandattributeformorecustomizationofCalendarView.Finallyweperform
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
295
setOnDateChangeListenereventtobenotifieduponselecteddatechange.Wheneverauser
tap/clickonanydatetheselecteddatewillbedisplayedbyusingaToast.
BelowyoucandownloadtheAndroidStudioprojectcode,seefinaloutputandstepbystep
explanation:
Step1:C
reateanewprojectandnameitCalendarViewExample
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
296
<RelativeLayoutx
mlns:android ="
http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
=".MainActivity" >
<!--
CalendarView with mondayasfirst day
andminmal
andmaximal
day
-->
<CalendarView
android:id
="@+id/simpleCalendarView"
android:layout_width
="
fill_parent"
android:layout_height
="fill_parent"
android:firstDayOfWeek
="2"
android:maxDate
="01/01/2018"
android:minDate
="01/01/2016" />
</RelativeLayout>
Step3:Open src->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodetoinitiatetheCalendarView.Inthisweset
selectedweekbackgroundcolorandweekseparatorlinecolorandfinallyperform
setOnDateChangeListenereventtobenotifieduponselecteddatechange.Wheneverauser
tap/clickonanydatetheselecteddatewillbedisplayedbyusingaToast.
package
example.abhiandroid .c
alenderviewexample ;
import
android .g
raphics .Color ;
import
android .g
raphics .drawable .Drawable;
import
android .s
upport .v
7 .a
pp .A
ppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .M
enu;
import
android .v
iew .M
enuItem ;
import
android .w
idget .C
alendarView ;
import
android .w
idget .T
oast ;
public
c
lassM
ainActivity extends A
ppCompatActivity {
CalendarView
simpleCalendarView ;
@Override
protected
voidonCreate (Bundle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.l
ayout .a
ctivity_main );
s
impleCalendarView= (C
alendarView )findViewById (R
.i
d
.s
impleCalendarView);
/
/
get
the
reference ofCalendarView
s
impleCalendarView .s
etFocusedMonthDateColor (C
olor .RED
);/
/
set
the
red
color
for
the
dates
of focused month
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
297
s
impleCalendarView .setUnfocusedMonthDateColor (Color.BLUE
);/
/set theyellowcolor
for
thedates ofanunfocused month
s
impleCalendarView .setSelectedWeekBackgroundColor (C
olor.RED
);/
/redcolorforthe
selected week's background
s
impleCalendarView .setWeekSeparatorLineColor (C
olor .GREEN
);/
/green colorforthe
weekseparator line
//
perform setOnDateChangeListener eventonCalendarView
s
impleCalendarView .setOnDateChangeListener(n
ewCalendarView .OnDateChangeListener (){
@Override
public v
oid
onSelectedDayChange (C
alendarView view,i
nt
year ,i
nt
month,int
dayOfMonth ){
//
display the
selected
dateby
using a
toast
Toast
.makeText (g
etApplicationContext (),
dayOfMonth +"/"+
month+"
/"+
year
,Toast.L
ENGTH_LONG ).
show ();
}
});
}
}
Output:
NowruntheappandyouwillseeCalendaropen.Nowclickonanydateanditwilldisplayedon
thescreenasToast.Alsotryscrollingupanddowntoseethemaximumandminimumdateset
forCalendar.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
298
ExpandableListView
InAndroid,ExpandableListViewisaViewthatshowsitemsinaverticallyscrollingtwolevel
list.Differentfromthelistviewbyallowingtwolevelgroupswhichcanindividuallybeexpanded
toshowitschildren.Eachgroupcanbeexpandedorcollapsedindividuallytoshoworhideits
childrenitems.
WecanattachlistenerseventstotheExpandableListViewtolistenforOnClickoranyother
eventsontheGrouportheindividualchildren. Adaptersareusedtosupplyorcontrolthedata
thatwillbedisplayedinanExpandableListView.
ImportantNote:Y
oucannotusethevaluewrap_contentfortheheightattributeofa
ExpandableListViewinXMLiftheparent’ssizeisnotstrictlyspecified.Inotherwordswemean
iftheparentwereScrollViewthenyoucouldnotspecifywrap_contentsinceitcanbeofany
length.However,youcanusewrapcontentiftheExpandableListViewparenthasaspecificsize,
suchas200pixels.
ExpandableListViewcodeinXML:
<ExpandableListView
android:id
="
@+id/simpleExpandableListView"
android:layout_width="
fill_parent"
android:layout_height="fill_parent"
/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
299
AttributesofExpandableListViewInAndroid
Nowlet’swediscussaboutsomeimportantattributesthathelpsustoconfigurea
ExpandableListViewinXMLfile(layout).
1.id:idisanattributeusedtouniquelyidentifyaExpandableListView.
<ExpandableListView
android:id
="
@+id/simpleExpandableListView"
android:layout_width ="
fill_parent"
android:layout_height ="fill_parent"
/>
<
!-- i
d
of
an
attribute
used
to
uniquely
identify
a
expandablelist
view-->
2.divider:T
hisisadrawableorcolortodrawbetweendifferentgrouplistitems.
Belowwedrawredcolordividerbetweendifferentgroupitems.
<ExpandableListView
android:id
="
@+id/simpleExpandableListView"
android:layout_width="
match_parent"
android:layout_height="fill_parent"
android:divider
="
#f00"
android:dividerHeight="1dp"
/
>
"/><
!-- r
ed
color
divider
with
1dp
height
between
the
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
300
groups
items
of e
xpandable
list
view
-->
3.dividerHeight:Thisspecifytheheightofthedividerbetweengrouplistitems.Thiscould
beindp(densitypixel),sp(scaleindependentpixel)orpx(pixel).
Inaboveexampleofdividerwealsosetthedividerheight1dpbetweenthelistitems.The
heightshouldbeindp,sporpx.
4.listSelector:ThispropertyisusedtosettheselectoroftheexpandablelistView.Itis
generallyorangeorSkybluecolormostlybutyoucanalsodefineyourowncustomcolororan
imageasalistselectorasperyourdesign.
Belowselectorcolorisgreen,whenyouselectanylistitemthenthatitem’sbackgroundcoloris
green.
<ExpandableListView
android:id
="
@+id/simpleExpandableListView"
android:layout_width="
match_parent"
android:layout_height="fill_parent"
android:divider
="
#f00"
android:dividerHeight="1dp"
android:listSelector="
#0f0"/>
<
!-- g
reen
color
for
the
list
selector
item
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
301
5.childDivider:T
hisisadrawableorcolortodrawbetweendifferentchildlistitemsofa
expandablelistview.
Belowwedrawgreencolordividerbetweendifferentchilditemsofagroup.
<ExpandableListView
android:id
="
@+id/simpleExpandableListView"
android:layout_width
="match_parent"
android:layout_height
="fill_parent"
android:divider
="#f00"
android:dividerHeight
="1dp"
android:childDivider
="#0f0"
/>
<
!-- g
reen
color
divider
between
the
child
items
of
expandable
listview-->
ThebelowimageisfromtheExpandableListViewexamplewhichisexplainedattheendofthis
post.InthiswehavesetgreencolorasChilddividerandredcolorasdivider.Thereasonwe
haveusedthisexampleimagebecauseweneedfilldatausingAdaptertoshowyouchildDivider
attributeinaction.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
302
6.padding:p
addingattributeisusedtosetthepaddingfromleft,right,toporbottom.
paddingRight:setthepaddingfromtherightsideoftheexpandablelistview.
paddingLeft:setthepaddingfromtheleftsideoftheProgressbar.
paddingTop:s etthepaddingfromthetopsideoftheexpandablelistview.
paddingBottom:setthepaddingfromthebottomsideoftheexpandablelistview.
Padding:s etthepaddingfromtheallside’softheexpandablelistview.
Belowwesetthe50dppaddingfromalltheside’softheexpandablelistview.
<ExpandableListView
android:id
="
@+id/simpleExpandableListView"
android:layout_width="
match_parent"
android:layout_height="fill_parent"
android:divider
="
#f00"
android:dividerHeight="2dp"
android:childDivider="
#0f0"
android:padding
="
50dp"/>
<
!-- 5
0
dp
padding
from
all
the
sides
of
a
expandable
list
view
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
303
AdapterUsedInExpandableListViewInAndroid:
AnadapterisabridgebetweenUIcomponentanddatasourcethathelpsustofilldatainUI
component.ItholdsthedataandsendthedatatoAdapterviewthenviewcantakesthedata
fromtheadapterviewandshowsthedataondifferentviewslikeasExpandableListViewor
otherViews.Theimplementationofthisinterfacewillprovideaccesstothedataofthechildren
(categorizedbygroups),andalsoinstantiateviewsforthechildrenandgroups.
InAndroidforsupplyingdatainanExpandableListViewfollowingadaptersareused.
1.ExpandableListAdapter
2.BaseExpandableListAdapter
3.SimpleExpandableListAdapter
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
304
Nowweexplainthesethreeadaptersindetail:
1.ExpandableListAdapter:
ExpandableListAdapterisanAdapterthatlinksaExpandableListViewwiththeunderlyingdata.
Theimplementationofthisinterfacewillprovidethedataforthechildrenandalsoinitiatethe
viewsforthechildrenandgroups. Forcustomizationoflistweneedtoimplement
ExpandableListAdapterinourcustomadapter.
BelowistheexamplecodeofExpandableListAdapterinwhichwecreateCustomAdapterclass
andthenimplementsExpandableListAdapterinthatclass.
public
c
lass C
ustomAdapterimplements
E
xpandableListAdapter {
@Override
public
v
oid registerDataSetObserver (D
ataSetObserver
observer){
}
@Override
public
v
oid unregisterDataSetObserver (DataSetObserver
observer){
}
@Override
public
i
nt
getGroupCount ()
{
return
0
;
}
@Override
public
i
nt
getChildrenCount (i
nt
groupPosition ){
return
0
;
}
@Override
public
O
bject getGroup
(i
nt
groupPosition ){
return
n
ull ;
}
@Override
public
O
bject getChild
(i
nt
groupPosition ,i
nt
childPosition ){
return
n
ull ;
}
@Override
public
l
ong getGroupId(i
nt
groupPosition ){
return
0
;
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
305
@Override
public
l
ong
getChildId(i
nt
groupPosition ,i
nt
childPosition ){
return
0
;
}
@Override
public
b
oolean
hasStableIds (){
return
f
alse;
}
@Override
public
V
iew
getGroupView (i
nt
groupPosition ,boolean
isExpanded ,View
convertView,V
iewGroup
parent
){
return
n
ull;
}
@Override
public
V
iew
getChildView (i
nt
groupPosition ,int
childPosition ,boolean
isLastChild
,V
iew
convertView,ViewGroup
parent ){
return
n
ull;
}
@Override
public
b
oolean
isChildSelectable (int
groupPosition ,i
nt
childPosition ){
return
f
alse;
}
@Override
public
b
oolean
areAllItemsEnabled ()
{
return
f
alse;
}
@Override
public
b
oolean
isEmpty
(){
return
f
alse;
}
@Override
public
v
oid
onGroupExpanded (intgroupPosition ){
}
@Override
public
v
oid
onGroupCollapsed (i
nt
groupPosition ){
}
@Override
public
l
ong
getCombinedChildId (l
onggroupId,l
ong
childId){
return
0
;
}
@Override
public
l
ong
getCombinedGroupId (l
onggroupId){
return
0
;
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
306
ReadE
xpandableListAdapterTutorialWithExampleInAndroidStudioformoredetails.
2.BaseExpandableListAdapter:
BaseExpandableListAdapterisabaseclassfortheexpandablelistadapterusedtoprovidedata
andViewsfromsomedatatoExpandableListView.ForCreatingacustomExpandableListView
weneedtocreateacustomclassandthenextendsBaseExpandableListAdapterclassinthat
class.
BelowisanexamplecodeofBaseExpandableListAdapterinwhichwecreatecustomadapter
classandthenextendsBaseExpandableListAdapterinthatclass.
public
c
lass C
ustomAdapterextends B
aseExpandableListAdapter {
@Override
public
i
nt
getGroupCount ()
{
return
0
;
}
@Override
public
i
nt
getChildrenCount (i
nt
groupPosition){
return
0
;
}
@Override
public
O
bject getGroup
(i
nt
groupPosition ){
return
n
ull ;
}
@Override
public
O
bject getChild
(i
nt
groupPosition ,i
nt
childPosition
){
return
n
ull ;
}
@Override
public
l
ong getGroupId(i
nt
groupPosition ){
return
0
;
}
@Override
public
l
ong getChildId(i
nt
groupPosition ,i
nt
childPosition
){
return
0
;
}
@Override
public
b
oolean
hasStableIds(){
return
f
alse ;
}
@Override
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
307
public
V
iew
getGroupView (i
nt
groupPosition,b
oolean
isExpanded
,View
convertView,V
iewGroup
parent
){
return
n
ull;
}
@Override
public
V
iew
getChildView (i
nt
groupPosition,i
nt
childPosition
,b
oolean
isLastChild
,V
iew
convertView,ViewGroup
parent){
return
n
ull;
}
@Override
public
b
oolean
isChildSelectable (i
nt
groupPosition
,i
nt
childPosition){
return
f
alse;
}
}
ReadB
aseExpandableListAdapterWithExampleInAndroidStudioforexplanationofallthese
function.
3.SimpleExpandableListAdapter:
SimpleExpandableListAdapterisanadapterthatisusedtomapthestaticdatatogroupand
childviewsdefinedinourXML(layout)file.Wecanseparatelyspecifythedatabackingtothe
groupasaListofMaps.EachentryinaArrayListcorrespondstoonegroupintheExpandable
List.Themapscontainsthedataforeachrow.WecanalsospecifyanXMLfilethatdefinesthe
viewsusedtodisplayagroup,andamappingfromkeysintheMaptospecificviews.This
processissimilarforachild,exceptitisoneleveldeepersothedatabackingisspecifiedasa
List<list>,wherethefirstListiscorrespondstothegroupofthechildandthesecondList
correspondstothepositionofthechildwithinthatgroup,andfinallytheMapholdsthedata
fortheparticularchild.
public
S
impleExpandableListAdapter(C
ontext
context,L
ist
<?
e
xtendsM
ap<S
tring,?>>
groupData
,int
groupLayout
,S
tring
[]groupFrom
,i
nt
[]
groupTo
,L
ist<?
e
xtendsL
ist <?
extends
Map
<S
tring
,?>>>
childData
,i
nt
childLayout,S
tring
[]
childFrom
,i
nt[]
childTo)
ReadS
impleExpandableListAdaptertutorialforexplanationofalltheseparameter.
ExpandableListViewusingBaseExpandableListAdapterExampleInAndroid
Studio
BelowistheexampleofExpandableListViewinandroidwherewedisplayanexpandablelist
withsubjectnameandtheirtopics.InthisexamplewedisplaysubjectnamesasGroupitems
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
308
andtheirtopicnamesaschilditemsforaparticulargroup.Inthisweimplement
setOnChildClickListener()andsetOnGroupClickListener()eventsandwheneverauserclickson
achildoragroupitemthenameoftheitemisdisplayedbyusingaToast.
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanationofExamplein
AndroidStudio:
Step1:C
reateanewprojectandnameitExpandableListViewExample.
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepweopenanXMLfileandaddthecodefordisplayingaExpandableListViewbyusing
itsdifferentattributes.
<?
xml
version
="
1.0"
encoding ="
UTF-8"?>
<RelativeLayoutx
mlns:android ="http://schemas.android.com/apk/res/android"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:orientation
="vertical" >
<ExpandableListView
android:id
="
@+id/simpleExpandableListView"
android:layout_width
="
match_parent"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
309
ndroid:layout_height
a ="fill_parent"
android:divider
="
#f00"
android:childDivider
="#0f0"
android:dividerHeight
="1dp"
/>
</RelativeLayout>
Step3:CreateanewxmlfileforgroupitemsOpenres->layout->group_items.xmlandadd
followingcode:
InthisstepweaddthecodefordisplayingaTextViewsubjectnames.
<?
xml
version
="
1.0"
encoding="
utf-8" ?>
<LinearLayout
xmlns:android="
http://schemas.android.com/apk/res/android"
android:layout_width
="fill_parent"
android:layout_height
="
55dip"
android:orientation
="
vertical" >
<TextView
android:id
="
@+id/heading"
android:layout_width
="wrap_content"
android:layout_height
="
wrap_content"
android:paddingLeft
="
35sp"
android:textAppearance
="?android:attr/textAppearanceLarge"
android:textStyle
="
bold" /
>
</LinearLayout>
Step4:C
reateanewxmlfileforgroupitemsOpenres->layout->child_items.xmlandadd
followingcode:
InthisstepweaddthecodefordisplayingtwoTextViewi.e.oneforsequenceoftopicsand
anotherfortopicname
<?
xml
version
="
1.0"
encoding
="
utf-8"?>
<RelativeLayouta
ndroid:layout_width="
match_parent"
a
ndroid:layout_height
="
match_parent"
android:orientation
="
vertical"
xmlns:android
="http://schemas.android.com/apk/res/android">
<TextView
android:id
="
@+id/sequence"
android:layout_width
="wrap_content"
android:layout_height
="
wrap_content"
android:layout_alignParentLeft
="
true"
android:layout_alignParentTop
="true"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
310
ndroid:paddingLeft
a ="
35sp"
android:textAppearance
="
?android:attr/textAppearanceMedium"
/
>
<TextView
android:id
="
@+id/childItem"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:layout_alignParentTop
="
true"
android:layout_toRightOf
="
@id/sequence"
android:textAppearance
="
?android:attr/textAppearanceMedium"
/
>
</RelativeLayout>
Step5:O
pen src->package->MainActivity.Java
InthisstepweopenMainActivityandaddthecodetoinitiatetheExpandableListViewandadd
thedatatolistsfordisplayinginanExpandableListViewusingmodelclassesandthensetthe
adapterwhichfillsthedataintheExpandableListView.Inthisweimplement
setOnChildClickListener()andsetOnGroupClickListener()events.Wheneverauserclicksona
childoragroupitemthenameoftheitemisdisplaybyusingaToast.
package
example .a
bhiandroid .expandablelistviewexample ;
import
android .os
.B
undle ;
import
android .support .v
7.app.A
ppCompatActivity ;
import
android .view.View;
import
android .widget .E
xpandableListView ;
import
android .widget .T
oast ;
import
java .u
til .A
rrayList ;
import
java .u
til .L
inkedHashMap ;
public
c
lass M
ainActivity extends A
ppCompatActivity {
private
L
inkedHashMap <String ,GroupInfo >subjects= newL
inkedHashMap
<S
tring
,
GroupInfo >();
private
A
rrayList <G
roupInfo >deptList= n
ewA
rrayList <G
roupInfo>();
private
C
ustomAdapter listAdapter ;
private
E
xpandableListView
simpleExpandableListView ;
@Override
public
v
oid
onCreate (Bundle
savedInstanceState ){
super
.o
nCreate (savedInstanceState );
s
etContentView (R.
layout .a
ctivity_main );
//
add data fordisplaying in
expandable listview
l
oadData ();
//get
reference of theExpandableListView
s
impleExpandableListView= (E
xpandableListView )
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
311
findViewById (R.
i
d.simpleExpandableListView );
//
create the adapter bypassing your ArrayList data
l
istAdapter =n ewCustomAdapter (MainActivity .this
,deptList );
//
attach the adapter totheexpandable list view
s
impleExpandableListView .s
etAdapter (l
istAdapter );
//expand
all the Groups
e
xpandAll ();
//
setOnChildClickListener listener forchild rowclick
s
impleExpandableListView .s
etOnChildClickListener (n
ew
ExpandableListView .O
nChildClickListener () {
@Override
public b
oolean
onChildClick (ExpandableListView
parent,View
v,i
nt
groupPosition ,int
childPosition ,long
id ){
//get
the group header
GroupInfo
headerInfo = deptList .g
et (g
roupPosition );
//get
the child info
ChildInfo
detailInfo = h eaderInfo .getProductList ().get
(c
hildPosition );
//display
itor do
something withit
Toast
.makeText (g
etBaseContext (),
"Clicked on::
"+headerInfo .g
etName
()
+"
/"+detailInfo .g
etName (),Toast.L
ENGTH_LONG ).
show();
return
f
alse ;
}
});
//
setOnGroupClickListener listener forgroup heading click
s
impleExpandableListView .s
etOnGroupClickListener (n
ew
ExpandableListView .O
nGroupClickListener () {
@Override
public b
oolean
onGroupClick (ExpandableListView
parent,View
v,i
nt
groupPosition ,long id){
//get
the group header
GroupInfo
headerInfo = deptList .g
et (g
roupPosition );
//display
itor do
something withit
Toast
.makeText (g
etBaseContext (),
"Header is::
"+headerInfo.getName
(),
Toast
.LENGTH_LONG ).
show ();
return
f
alse ;
}
});
}
//method
toexpand all groups
private
v
oid expandAll ()
{
int
count=
listAdapter .getGroupCount ();
for
(
inti=0;i<
count ;
i++){
s
impleExpandableListView .expandGroup (i)
;
}
}
//method
tocollapse allgroups
private
v
oid collapseAll (){
int
count=
listAdapter .getGroupCount ();
for
(
inti=0;i<
count ;
i++){
s
impleExpandableListView .collapseGroup (i)
;
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
312
}
/load
/ some
initialdatainto
out
list
private
v
oid
loadData
(){
a
ddProduct
("
Android"
,"
ListView"
);
a
ddProduct
("
Android"
,"
ExpandableListView"
);
a
ddProduct
("
Android"
,"
GridView"
);
a
ddProduct
("
Java"
,"
PolyMorphism"
);
a
ddProduct
("
Java"
,"
Collections"
);
}
/here
/ we
maintain
ourproducts
in
variousdepartments
private
i
nt
addProduct
(S
tring
department
,S
tring
product
){
int
groupPosition=
0
;
/check
/ the
hash mapifthe
group already exists
GroupInfo
headerInfo =
subjects .g
et (department);
//add
the
group if
doesn't exists
if
(h
eaderInfo= =
null
){
h
eaderInfo=new
G
roupInfo ();
h
eaderInfo.s
etName (d
epartment );
s
ubjects
.put
(department ,
headerInfo );
d
eptList
.add
(headerInfo );
}
/get
/ thechildrenfor
thegroup
ArrayList
<C
hildInfo>
productList= headerInfo
.g
etProductList
();
//size
of
thechildren
list
int
listSize=productList
.size
();
//add
tothe
counter
l
istSize++;
/create
/ anew
child
and
add that
to
thegroup
ChildInfo
detailInfo=n
ew
ChildInfo();
d
etailInfo
.s
etSequence(S
tring .v
alueOf
(l
istSize));
d
etailInfo
.s
etName(p
roduct
);
p
roductList
.add
(d
etailInfo
);
h
eaderInfo
.s
etProductList(p
roductList );
/find
/ the
grouppositioninside
the
list
g
roupPosition=
deptList.i
ndexOf(h
eaderInfo
);
return
groupPosition ;
}
}
Step6:C
reateaNewClassOpen->package–>GroupInfo.Javaandaddthefollowingcode.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
313
Inthisstep,wecreateaclassforsettingandgettingthegroupitemnameandchilditemsinfo
accordingtoaparticulargroup.GroupInfoisamodelclassusedtosetthenameofthegroup
itemandchilditemsinformationfromyourmainactivityandthengettheinformationwithin
Adapterclass.FinallysetthevaluetoExpandableListView.
packageexample .a
bhiandroid .expandablelistviewexample ;
import
java.u
til .A
rrayList ;
publicc
lassGroupInfo {
private
S
tring
name ;
private
A
rrayList <ChildInfo >list=n
ewA
rrayList <C
hildInfo
>();
public
S
tring
getName ()
{
return
name ;
}
public
v
oid
setName (String
name){
this
.n
ame= name ;
}
public
A
rrayList <ChildInfo >getProductList ()
{
return
list ;
}
public
v
oid
setProductList (A
rrayList <ChildInfo>productList
){
this
.l
ist= productList ;
}
}
Step7:CreateaNewClassOpen->package–>ChildInfo.Javaandaddthefollowingcode.
Inthisstep,wecreateaclassforsettingandgettingthenameandsequenceforthechilditems.
ChildInfoisamodelclassusedtosetthenameofthechilditemandthesequenceofthechild
itemfromyourmainactivityandthengetthenameandsequencewithinadapterclass.Finally
setthevaluetoexpandablelistview.
package
example
.abhiandroid .e
xpandablelistviewexample
;
public
c
lassC
hildInfo{
private
S
tring
sequence= ""
;
private
S
tring
name="
";
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
314
public
S
tring
getSequence
()
{
return
sequence
;
}
public
v
oid
setSequence
(S
tring
sequence
){
this
.s
equence=
sequence
;
}
public
S
tring
getName
()
{
return
name;
}
public
v
oid
setName
(S
tring
name
){
this
.n
ame=
name
;
}
}
Step8:C
reateaNewClassOpen->package–>CustomAdapter.Javaandaddthefollowing
code.
Inthisstep,wecreateaCustomAdapterclassandthenextendsBaseExpandableListAdapterin
thatclass.FinallysetthedataintheExpandableListViewfromGroupInfoand ChildInfomodel
class.
package example .a
bhiandroid .expandablelistviewexample ;
import
android .content .C
ontext ;
import
android .view .L
ayoutInflater ;
import
android .view .V
iew ;
import
android .view .V
iewGroup ;
import
android .widget .B
aseExpandableListAdapter ;
import
android .widget .T
extView ;
import
java.u
til .A
rrayList ;
/**
*
Created by Gourav on08-03-2016.
*/
public c
lassCustomAdapter e
xtends B
aseExpandableListAdapter {
private
C
ontext
context ;
private
A
rrayList <G
roupInfo >deptList
;
public
C
ustomAdapter (C
ontext context
,A
rrayList <G
roupInfo
>deptList
){
this
.c
ontext= context ;
this
.d
eptList= deptList ;
}
@Override
public
O
bject
getChild (i
ntgroupPosition,i
nt
childPosition ){
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
315
rrayList
A <C
hildInfo
>
productList=
deptList
.g
et
(g
roupPosition
).
getProductList
();
return
productList
.g
et
(c
hildPosition
);
}
Override
@
public
l
ong
getChildId
(i
nt
groupPosition
,i
nt
childPosition
){
return
childPosition;
}
Override
@
public
V
iew
getChildView
(i
nt
groupPosition,i
nt
childPosition
,b
oolean
isLastChild
,
V
iew
view
,V
iewGroup
parent
){
hildInfo
C detailInfo =(ChildInfo )
getChild (g
roupPosition ,
childPosition );
if
(
v
iew= =n
ull
){
LayoutInflater infalInflater= (
LayoutInflater )
context.g
etSystemService (Context .LAYOUT_INFLATER_SERVICE );
v
iew= infalInflater .i
nflate (R
.l
ayout .c
hild_items ,n
ull);
}
TextView
sequence= (T
extView )
view.findViewById (R
.id
.s
equence );
s
equence .s
etText(detailInfo .g
etSequence ().trim()+
"."
);
TextView
childItem= (
TextView )
view .f
indViewById (R.i
d
.childItem);
c
hildItem .setText(d
etailInfo .getName().trim());
return
view ;
}
@Override
public
i
ntgetChildrenCount (int
groupPosition ){
ArrayList
<ChildInfo >
productList=
deptList .g
et
(groupPosition ).getProductList();
return
productList .size();
}
@Override
public
O
bject
getGroup (int
groupPosition ){
return
deptList .g
et(groupPosition );
}
@Override
public
i
ntgetGroupCount ()
{
return
deptList .s
ize ();
}
@Override
public
l
ong
getGroupId (int
groupPosition ){
return
groupPosition ;
}
@Override
public
V
iew
getGroupView (i
nt
groupPosition ,booleanisLastChild ,V
iew
view
,
V
iewGroup
parent ){
GroupInfo
headerInfo =(GroupInfo )
getGroup (g
roupPosition );
if
(
v
iew= =n
ull
){
LayoutInflater inf=(LayoutInflater )
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
316
context.g
etSystemService (Context.LAYOUT_INFLATER_SERVICE );
v
iew=
inf.i
nflate (R
.l
ayout .g
roup_items,n
ull);
}
TextView
heading= (
TextView )view.f
indViewById(R
.i
d.h
eading
);
h
eading .setText(h
eaderInfo .getName ().
trim
());
return
view;
}
@Override
public
b
oolean
hasStableIds (){
return
t
rue;
}
@Override
public
b
oolean
isChildSelectable (i
ntgroupPosition,i
ntchildPosition
){
return
t
rue;
}
}
Output:
NowruntheAppandyouwillseemaintopicsandsub-topicslistedinExpandableListView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
317
Chronometer
InAndroid,Chronometerisaclassthatimplementsasimpletimer.Chronometerisasubclass
ofTextView.Thisclasshelpsustoaddatimerinourapp.
YoucangiveTimerstarttimeintheelapsedRealTime()timebaseanditstartcountingfrom
that.Ifwedon’tgivebasetimethenitwillusethetimeatwhichtimewecallstart()method.By
defaultachronometerdisplaysthecurrenttimervalueintheformofMM:SSorH:MM:SS.We
cansetourownformatintoanarbitrarystring.
ChronometercodeinXML:
<Chronometer
android:id
="
@+id/simpleChronometer"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"/
>
MethodsOfChronometerInAndroid:
Let’sdiscusssomeimportantmethodsofchronometerthatmaybecalledinordertomanage
thechronometer.
1.start():s tartfunctionofchronometerisusedtostartthecountingup.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
318
Belowwestartthecountingupofachronometer.
Chronometer
simpleChronometer=
(
Chronometer
)
findViewById
(R
.i
d
.s
impleChronometer
);
/
/
initiate
a
chronometer
simpleChronometer
.s
tart
();
/
/
starta
chronometer
2.stop():s topfunctionofchronometerisusedtostopthecountingup.
Belowcodestopthecountingofachronometer.
Chronometer
simpleChronometer=(
Chronometer)
findViewById
(R
.i
d
.s
impleChronometer
);
/
/
initiate
a
chronometer
simpleChronometer
.s
top
();
/
/
stop a
chronometer
3.setFormat(Stringformat):s etformatfunctionofchronometerisusedtosettheformat
stringusedtodisplay.Inotherwordswecansayitisusedtodisplaytext,numbersetc
along-withchronometer.
Inthebelowexamplecodewesetthestringformatfordisplayingachronometer.
Chronometer
simpleChronometer=(
Chronometer
)
findViewById(R
.i
d
.s
impleChronometer);
/
/
initiate
a
chronometer
simpleChronometer
.s
tart
();
/
/starta
chronometer
simpleChronometer
.s
etFormat
("TimeRunning
-
%s");
/
/
set
theformat
for
a
chronometer
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
319
4.getformat():Thisfunctionofchronometerisusedforgettingthecurrentformatstring.
Thismethodsreturnsastringtypevalue.
Belowwegetthecurrentformatstringfromachronometer.
simpleChronometer=(
Chronometer
)
findViewById(R
.i
d
.s
impleChronometer
);
/
/initiate
a
chronometer
String
formatType
=s
impleChronometer .g
etFormat
();/
/
get
the
format
froma
chronometer
5.setOnChronometerTickListener(Chronometer.OnChronometerTickListener
listener):T
hisisalistenereventwhichisautomaticallycalledwhenthechronometerchanges.
BelowweshowtheuseofsetOnChronometerTickListener()forachronometer.
Chronometer
simpleChronometer=(
Chronometer
)
findViewById (R
.i
d.s
impleChronometer
);
/
/
initiate
a
chronometer
//
perform
set
onchronometer
ticklistener
eventof
chronometer
simpleChronometer
.s
etOnChronometerTickListener (new
C
hronometer .O
nChronometerTickListener()
{
@Override
public
v
oid
onChronometerTick(C
hronometer
chronometer){
//
do
something
whenchronometerchanges
}
});
6.setBase(longbase):s etbasefunctionofchronometerisusedtosetthetimethatcountup
timeisinreferenceto.YoucangiveitastarttimeintheelapsedRealtime()timebase,andit
countsupfromthat,orifyoudon’tgiveitabasetime,itwillusethetimeatwhichyoucall
start().
SystemClock.elapsedRealtime()i sthenumberofmillisecondssincethedevicewasturnedon.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
320
Belowwesetthebasetimeforachronometer.
Chronometer
simpleChronometer=
(
Chronometer
)
findViewById
(R.
id
.s
impleChronometer);
/
/
initiate
a
chronometer
simpleChronometer
.s
etBase
(S
ystemClock.e
lapsedRealtime
());
//setbase
time
for
a
chronometer
7.getBase():getbasefunctionisusedtogetthebasetimefromachronometer.Thismethod
returnsabasetimeassetthroughthesetBase()function.Thismethodreturnlongvalue.
Belowwegetthebasetimefromachronometer.
ChronometersimpleChronometer=(Chronometer)findViewById(R.id.simpleChronometer);
//initiateachronometer
longbase=simpleChronometer.getBase();//getbasetimefromachronometer
AttributesofChronometerInAndroid:
Nowlet’swediscusssomecommonattributesofachronomterthathelpsustoconfigureitin
ourlayout(xml).
1.Id:idattributeisusedtouniquelyidentifyachronometer.
<Chronometer
android:id
="
@+id/simpleChronometer"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"/
>
2.gravity:Thegravityattributeisanoptionalattributewhichisusedtocontrolthealignment
ofthetextlikeleft,right,center,top,bottom,center_vertical,center_horizontaletc.
Belowwesetthecenter_horizontalgravityfortextofachronometer.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
321
<Chronometer
android:id
="
@+id/simpleChronometer"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:gravity="center_horizontal"/
>
<!--
center
horizontal
gravity
for
the
text
of
chronometer-->
3.textColor:textColorattributeisusedtosetthetextcolorofchronometer.Colorvalueisin
theformof“#argb”,“#rgb”,“#rrggbb”,or“#aarrggbb”.
Belowwesettheredcolorforthedisplayedtextofachronometer.
<Chronometer
android:id
="
@+id/simpleChronometer"
android:layout_width="
fill_parent"
android:layout_height="wrap_content"
android:gravity
="
center_horizontal"
android:textColor="
#f00"/>
<!--
red
color
for
the
text
of
chronometer
-->
SettingtextColorofChronometerInJavaclass:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
322
ChronometersimpleChronometer=(Chronometer)findViewById(R.id.simpleChronometer);
//initiateachronometer
simpleChronometer.setTextColor(Color.RED);//setredcolorforthedisplayedtextofa
chronometer
4.textSize:textSizeattributeisusedtosetthesizeoftextofchronometer.Wecansetthetext
sizeinsp(scaleindependentpixel)ordp(densitypixel).
Belowwesetthe25spsizeforthetextofachronometer.
<Chronometer
android:id
="
@+id/simpleChronometer"
android:layout_width="
fill_parent"
android:layout_height="wrap_content"
android:gravity
="
center_horizontal"
android:textColor="
#f00"
android:textSize
="25sp"/>
<!--
25
sp size
for
displayed
text
of
chronometer
-->
SettingtextSizeofChronometerInJavaclass:
Chronometer
simpleChronometer=
(
Chronometer
)
findViewById(R
.i
d
.s
impleChronometer
);
/
/
initiate
a
chronometer
simpleChronometer
.s
etTextSize
(2
5
);/
/
set
textsize
of
a
chronometer
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
323
5.textStyle:t extStyleattributeisusedtosetthetextstyleofachronometer.Thepossibletext
stylesarebold,italicandnormal. Ifweneedtousetwoormorestylesforachronomtertext
then“|”operatorisusedforthat.
Belowwesettheboldanditalictextstylesfortextofachronometer.
<Chronometer
android:id
="
@+id/simpleChronometer"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_centerHorizontal ="
true"
android:textColor ="#f00"
android:textSize ="
25sp"
android:textStyle ="bold|italic"/>
<!--
bold
and
italic
style
for
displayed
text
of
chronometer-->
6.background:b ackgroundattributeisusedtosetthebackgroundofachronometer.You
cansetacolororadrawableinthebackgroundofatextview.Youcanalsosetthebackground
colorprogrammaticallymeansinjavaclass.
Belowwesetthegreencolorforthebackgroundofachronometer.
<Chronometer
android:id
="
@+id/simpleChronometer"
android:layout_width
="50dp"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
324
android:layout_height="
wrap_content"
android:layout_centerHorizontal="true"
android:textColor
="#f00"
android:textSize
="
25sp"
android:textStyle
="bold|italic"
android:background
="#0f0"
/>
<!--
greenbackground
color
of
chronometer
-->
SettingbackgroundofChronometerInJavaclass:
Chronometer
simpleChronometer=
(
Chronometer
)
findViewById
(R
.i
d
.s
impleChronometer);
/
/
initiate
a
chronometer
simpleChronometer
.s
etBackgroundColor(C
olor
.G
REEN
);
/
/
set
green color
for
the
background
of
a
chronometer
7.padding:paddingattributeisusedtosetthepaddingfromleft,right,toporbottom.
paddingRight:setthepaddingfromtherightsideofthechronometer.
paddingLeft:setthepaddingfromtheleftsideofthechronometer.
paddingTop:s etthepaddingfromthetopsideofthechronometer.
paddingBottom:setthepaddingfromthebottomsideofthe
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
325
Padding:s etthepaddingfromtheallside’softhechronometer.
Belowweset20dppaddingfromthetopofachronometer.
<Chronometer
android:id
="
@+id/simpleChronometer"
android:layout_width="
50dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal ="true"
android:textColor
="#f00"
android:textSize
="
25sp"
android:textStyle
="bold|italic"
android:background
="#0f0"
android:paddingTop
="20dp"/>
<!--
20dp
padding
from
the
top
of
a
chronometer
-->
8.drawableBottom:d
rawableBottomisthedrawabletobedrawntothebelowofthetextof
chronometer.
9.drawableTop:drawableTopisthedrawabletobedrawntothetopofthetextofa
chronometer.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
326
10.drawableRight:drawableRightisthedrawabletobedrawntotherightsideofthetextof
achronometer.
11.drawableLeft:drawableLeftisthedrawabletobedrawntotheleftsideofthetextofa
chronometer.
Belowwesettheicontotheleftsideofthetextofchronometer.Makesuretosaveic_launcher
imageindrawablefolder.
<Chronometer
android:id
="
@+id/simpleChronometer"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_centerHorizontal ="true"
android:textColor="
#f00"
android:textSize
="25sp"
android:textStyle="
bold|italic"
android:background="
#0f0"
android:gravity
="
center"
android:padding
="
10dp"
android:drawableLeft ="
@drawable/ic_launcher"
/>
<!--
drawable
left
of
a
chronometer
-->
ChronometerExampleinAndroidStudio:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
327
Intheexampleofchronometerwedisplaychronometerwithfivebuttonsandperformclick
eventsonthatbuttons.Buttonsareusedtostart,stop,restart,setFormatandclearFormatof
chronometer.Belowisthefinaloutput,downloadprojectcodeandstepbystepexplanation.
Step1:C
reateanewprojectandnameitChronometerExample.
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthisstepweopenxmlfileandaddthecodefordisplayingachronometerwithfivebuttonsto
performoperationsonchronometer.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
x
mlns
:t
ools
="
http://schemas.android.com/tools"
a
ndroid
:l
ayout_width ="
match_parent"
a
ndroid
:l
ayout_height ="match_parent"
a
ndroid
:p
addingBottom ="@dimen/activity_vertical_margin"
a
ndroid
:p
addingLeft="@dimen/activity_horizontal_margin"
a
ndroid
:p
addingRight ="
@dimen/activity_horizontal_margin"
a
ndroid
:p
addingTop="
@dimen/activity_vertical_margin"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
328
t
ools
:c
ontext
="
.MainActivity">
<
TextView
a
ndroid
:i
d
="
@+id/textView1"
a
ndroid
:l
ayout_width ="
wrap_content"
a
ndroid
:l
ayout_height ="wrap_content"
a
ndroid
:l
ayout_alignParentTop ="
true"
a
ndroid
:l
ayout_centerHorizontal ="true"
a
ndroid
:l
ayout_marginTop ="
10dp"
a
ndroid
:t
ext="
@string/chronometerInAndroid"
a
ndroid
:t
extColor="#FF0000"
a
ndroid
:t
extSize="
20dp"
a
ndroid
:t
extStyle="bold" /
>
<
Button
a
ndroid
:i
d
="
@+id/startButton"
a
ndroid
:l
ayout_width="
200dp"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:l
ayout_below="
@+id/textView1"
a
ndroid
:l
ayout_centerHorizontal ="true"
a
ndroid
:l
ayout_marginTop ="
10dp"
a
ndroid
:t
ext="
@string/start"/>
<
Button
a
ndroid
:i
d
="
@+id/stopButton"
a
ndroid
:l
ayout_width="
200dp"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:l
ayout_below="
@+id/startButton"
a
ndroid
:l
ayout_centerHorizontal ="true"
a
ndroid
:l
ayout_marginTop ="
10dp"
a
ndroid
:t
ext="
@string/stop"/
>
<
Button
a
ndroid
:i
d
="
@+id/restartButton"
a
ndroid
:l
ayout_width="
200dp"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:l
ayout_below="
@+id/stopButton"
a
ndroid
:l
ayout_centerHorizontal ="true"
a
ndroid
:l
ayout_marginTop ="
10dp"
a
ndroid
:t
ext="
@string/restart"/
>
<
Button
a
ndroid
:i
d
="
@+id/setFormat"
a
ndroid
:l
ayout_width="
200dp"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:l
ayout_below="
@+id/restartButton"
a
ndroid
:l
ayout_centerHorizontal ="true"
a
ndroid
:l
ayout_marginTop ="
10dp"
a
ndroid
:t
ext="
@string/setFormat" /
>
<
Button
a
ndroid
:i
d
="
@+id/clearFormat"
a
ndroid
:l
ayout_width="
200dp"
a
ndroid
:l
ayout_height="wrap_content"
a
ndroid
:l
ayout_below="
@+id/setFormat"
a
ndroid
:l
ayout_centerHorizontal ="true"
a
ndroid
:l
ayout_marginTop ="
10dp"
a
ndroid
:t
ext="
@string/clearFormat" /
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
329
!--
< chronometer
withblack background andred
text
color
-->
<
Chronometer
a
ndroid:i
d
="
@+id/simpleChronometer"
a
ndroid:l
ayout_width ="
wrap_content"
a
ndroid:l
ayout_height ="wrap_content"
a
ndroid:l
ayout_below ="
@+id/clearFormat"
a
ndroid:l
ayout_centerHorizontal ="true"
a
ndroid:l
ayout_marginTop ="20dp"
a
ndroid:b
ackground="#000"
a
ndroid:g
ravity
="
center"
a
ndroid:p
adding
="
10dp"
a
ndroid:t
extColor="
#f00"
a
ndroid:t
extStyle="
bold" />
</RelativeLayout>
Step3:O
pen src->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodetoinitiatethechronometer,fivebuttonand
thenperformonclicklistenereventonbuttonstoperformstart,stopandotheroperationson
chronometerasdiscussedearlierinthispost.
package
example .abhiandroid .c
hronometerexample ;
import
android .o
s.B
undle ;
import
android .o
s.S
ystemClock ;
import
android .s
upport .v7.a
pp.AppCompatActivity ;
import
android .v
iew .Menu;
import
android .v
iew .MenuItem ;
import
android .v
iew .View;
import
android .w
idget .Button ;
import
android .w
idget .Chronometer ;
public
c
lassMainActivity extends A
ppCompatActivity {
Chronometer
simpleChronometer ;
Button
start , stop,restart ,setFormat , clearFormat ;
@Override
protected
void
onCreate (B
undle
savedInstanceState ){
super
.onCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .activity_main );
//
initiate views
s
impleChronometer= (
Chronometer )findViewById (R.
id.s
impleChronometer
);
s
tart= (B
utton )findViewById (R.
id
.startButton );
s
top= (
Button )findViewById (R.i
d.s
topButton );
r
estart= (B
utton )findViewById (R.
id
.restartButton );
s
etFormat= (B
utton )findViewById (R.
id
.setFormat );
c
learFormat =(B
utton )findViewById (R.
id
.clearFormat );
//
perform click e vent onstart button to
start achronometer
s
tart.setOnClickListener (n
ew V
iew .OnClickListener (){
@Override
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
330
public
v
oid
onClick
(V
iew
v){
//
TODOAuto-generatedmethod
stub
s
impleChronometer
.s
tart
();
}
});
/
/ performclick e
venton
stop
button
to
stop
thechronometer
s
top.s
etOnClickListener
(n
ewV
iew
.O
nClickListener
()
{
@Override
public
v
oid
onClick
(V
iew
v){
//
TODOAuto-generatedmethod
stub
s
impleChronometer
.s
top
();
}
});
/
/ perform
click e
vent
onrestart
button
to
set
the
basetime
on
chronometer
r
estart
.s
etOnClickListener
(n
ewV
iew
.O
nClickListener
()
{
@Override
public
v
oid
onClick
(V
iew
v){
//
TODOAuto-generatedmethod
stub
s
impleChronometer
.s
etBase
(S
ystemClock
.e
lapsedRealtime
());
}
});
/
/ performclick e
vent
on
set
Formatbutton
to
set
theformat
of
chronometer
s
etFormat
.s
etOnClickListener(n
ew
V
iew
.OnClickListener
()
{
@Override
public
v
oid
onClick
(V
iew
v){
//
TODOAuto-generatedmethod
stub
s
impleChronometer
.s
etFormat
("
Time
(%s)"
);
}
});
//
perform click eventonclear buttontoclear
the
current format
of
chronmeter
as
you
setthrough setformat
c
learFormat .setOnClickListener (newV
iew.O
nClickListener()
{
@Override
publicv
oid
onClick
(V
iew
v){
//
TODOAuto-generated method stub
s
impleChronometer .s
etFormat (n
ull
);
}
});
}
}
Step4:O
penres->values->strings.xml
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
331
Inthisstepweshowsthelistofstringsthatwillbeusedinourexample.
<resources>
<
stringn
ame=" app_name">C hronometerExample</string>
<
stringn
ame=" hello_world">H elloworld!</string>
<
stringn
ame=" action_settings">S ettings</string>
<
stringn
ame=" chronometerInAndroid">C hronometerInAndroid</string>
<
stringn
ame=" start">S tart</string>
<
stringn
ame=" stop">S top</string>
<
stringn
ame=" restart">R estart</string>
<
stringn
ame=" setFormat">S etFormat</string>
<
stringn
ame=" clearFormat">C learFormat</string>
</resources>
Output:
NowruntheAppandyouwillsee5buttonstostart,stop,restart,setformatandclearformatof
Chronometer.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
332
ZoomControls
InAndroid,ZoomControlsclassdisplaysimplesetofcontrolsthatisusedforzoomingand
providescallbacktoregisterforevents.ZoomControlshastwobuttonsZoomInandZoomOut
whichareusedtocontrolthezoomingfunctionality.
ZoomControlscodeinXML:
<ZoomControls
android:id
="
@+id/simpleZoomControl"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"/
>
ImportantMethodsOfZoomControls:
Nowlet’sdiscusssomecommonmethodswhichareusedtoconfigureZoomControlsinour
application.
1.hide():T
hismethodisusedtohidetheZoomControlsfromthescreen.Insomecaseswe
needtohidetheZoomControlsfromthescreensothatweusethisfunction.
2.show():T
hismethodisusedtoshowtheZoomControlswhichwehidefromthescreenby
usinghidemethod.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
333
BelowweshowtheuseofhideandshowmethodsofZoomControls:
Step1:I nthisexamplefirstinxmlfilewedisplayZoomControlswithtwobuttonshideand
showwhichareusedtohideandshowtheZoomControls.
xmlcodeofaboveimageUI:
<RelativeLayout x
mlns:android ="
http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools"
android:layout_width ="
match_parent"
android:layout_height ="match_parent"
android:paddingBottom ="@dimen/activity_vertical_margin"
android:paddingLeft ="@dimen/activity_horizontal_margin"
android:paddingRight ="
@dimen/activity_horizontal_margin"
android:paddingTop ="
@dimen/activity_vertical_margin"
tools:context="
.MainActivity" >
<ZoomControls
android:id
="
@+id/simpleZoomControl"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_centerHorizontal ="
true"
android:layout_marginTop ="
50dp"/
>
<Button
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
334
android:id
="
@+id/show"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:layout_centerInParent ="
true"
android:layout_margin ="20dp"
android:background="#0f0"
android:text="
Show"
android:textColor="#fff" /
>
<Button
android:id
="
@+id/hide"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:layout_below ="
@+id/show"
android:layout_margin ="20dp"
android:background="#f00"
android:text="
Hide"
android:textColor="#fff" /
>
</RelativeLayout>
Step2:N
owinJavaClassweusehide()andshow()methodstohideandshowZoomControls
option.
/*Add
belowsetContentView() method inOncreate()*/
final
ZoomControls
simpleZoomControls =(
ZoomControls )
findViewById(R.
i
d.s
impleZoomControl );/
/initiate a
ZoomControls
Button
show=(
B
utton)
findViewById (R
.i
d
.s
how );
/
/initiate
show
Button
Button
hide=(
B
utton)
findViewById (R
.i
d
.h
ide );
/
/initiate
hide
Button
//
performsetOnClickListener onshowbutton
s
how.setOnClickListener (new
V
iew .O
nClickListener ()
{
@Override
public void
onClick
(View
v)
{
//
show
a
ZoomControls
s
impleZoomControls .s
how ();
}
});
//
performsetOnClickListener onhidebutton
h
ide.setOnClickListener (new
V
iew .O
nClickListener ()
{
@Override
public void
onClick
(View
v)
{
//
hide
a
ZoomControls
s
impleZoomControls .h
ide ();
}
});
Output:
NowruntheAppandyoucanseeZoomControlscanbehidedandshowedagainfromuser.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
335
3.setOnZoomInClickListener(OnClickListenerlistener):T
hisisalistenerevent
automaticallycalledwhenweclickontheZoomInbuttonofZoomControls.Inthislistenerwe
addthecodetozoominimage.
BelowweshowtheuseofsetOnZoomInClickListenerinandroid.
final
Z
oomControls
simpleZoomControls
=(
ZoomControls)
findViewById
(R
.i
d.s
impleZoomControl
);
//
initiate a
ZoomControls
//
perform s etOnZoomInClickListenereventon
ZoomControls
simpleZoomControls .s
etOnZoomInClickListener(n
ew
V
iew
.OnClickListener
(){
@Override
publicv
oid
onClick (View
v)
{
//
addzoomincodehere
}
});
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
336
4.setOnZoomOutClickListener(OnClickListenerlistener):T
hisisalistenerevent
automaticallycalledwhenweclickontheZoomOutbuttonofZoomControls.Inthislistener
weaddthecodeforzoomoutaimage.
BelowweshowtheuseofsetOnZoomOutClickListenerinandroid.
final
Z
oomControls
simpleZoomControls
=(
ZoomControls
)findViewById
(R
.i
d
.simpleZoomControl
);
//
initiate a
ZoomControls
//
perform s etOnZoomOutClickListener
eventon
ZoomControls
simpleZoomControls .s
etOnZoomOutClickListener(n
ew
V
iew
.OnClickListener
(){
@Override
publicv
oid
onClick(View
v)
{
//
addzoomout
codehere
}
});
5.setIsZoomInEnabled(booleanisEnabled):T
hismethodisusedtoenableordisablethe
zoomInbuttonofZoomControls.InthismethodwesetaBooleanvalueeithertrueorfalse.By
defaultithastruevaluebutsometimeafteralimitofzoominweneedtodisablethezoomin
functionalityi.e.afterthatwedidn’tneedmorezoomin.
BelowwesetthefalsevalueforsetIsZoomInEnabledthatdisablezoominbuttonof
ZoomControls.
ZoomControls
simpleZoomControls=
(
ZoomControls)
findViewById
(R
.i
d
.s
impleZoomControl
);
/
/
initiate
a
ZoomControls
simpleZoomControls.s
etIsZoomInEnabled(f
alse
);
/
/disable
zoom
inbutton
of
ZoomControls
6.setIsZoomOutEnabled(booleanisEnabled):Thismethodisusedtoenableordisable
thezoomOutbuttonofZoomControls.InthismethodwesetaBooleanvaluemeanstrueor
false.Bydefaultithastruevaluebutsometimeafteralimitofzoomoutweneedtodisablethe
zoomoutfunctionalitymeansatthattimewedidn’tneedmorezoomout.
BelowwesetthefalsevalueforsetIsZoomOutEnabledthatdisablezoomoutbuttonof
ZoomControls.
ZoomControls
simpleZoomControls=
(
ZoomControls)
findViewById
(R
.i
d
.s
impleZoomControl
);
/
/
initiate
a
ZoomControls
simpleZoomControls.s
etIsZoomOutEnabled(f
alse
);
/
/disable
zoom
outbutton
of
ZoomControls
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
337
AttributesOfZoomControlsinAndroid:
Nowlet’s wediscusssomeimportantattributesthathelpsustoconfigureaZoomControlsin
ourxmlfile.
1.id:T
hisattributeisusedtouniquelyidentifyaZoomControls.
<ZoomControls
android:id
="
@+id/simpleZoomControl"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"/
>
<
!-- i
d
of
ZoomControls
used
to
uniquely
identify
it
-->
2.background:T
hisattributeisusedtosetthebackgroundofaZoomControls.Wecanseta
colororadrawableinthebackgroundofaZoomControls.
BelowwesettheblackcolorforthebackgroundofZoomControls.
<ZoomControls
android:id
="
@+id/simpleZoomControl"
android:layout_width="
wrap_content"
android:layout_height="wrap_content"
android:background
="
#000" /
>
<!--
set
black
colorinthe
background
of
a
ZoomControls
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
338
SettingbackgroundinZoomControlsInJavaclass:
ZoomControls
simpleZoomControls=
(
ZoomControls
)findViewById(R
.i
d
.s
impleZoomControl
);
/
/
initiate
a
ZoomControls
simpleZoomControls .s
etBackgroundColor(C
olor
.B
LACK);
/
/
set
black color
in
the
backgroundof
ZoomControls
3.padding:T
hisattributeisusedtosetthepaddingfromleft,right,toporbottomsideofa
ZoomControls.
paddingRight:setthepaddingfromtherightsideofaZoomControls.
paddingLeft:setthepaddingfromtheleftsideofaZoomControls.
paddingTop:setthepaddingfromthetopsideofaZoomControls.
paddingBottom:setthepaddingfromthebottomsideofaZoomControls.
Padding:s etthepaddingfromtheallside’sofaZoomControls.
Belowwesetthe20dppaddingfromallthesidesofaZoomControls.
<ZoomControls
android:id
="
@+id/simpleZoomControl"
android:layout_width="
wrap_content"
android:layout_height="wrap_content"
android:background
="
#000"
android:padding
="
20dp"/><!--
20dp
padding
from
all
the
sides
of
a
ZoomControls
-->
ZoomControlsExampleInAndroidStudio
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
339
BelowisanexampleofZoomControlsinwhichwedisplayanImageViewandaZoomControls.
InthisfirstwehidetheZoomControlsfromthescreenandshowitonthetoucheventofimage.
WealsoperformsetOnZoomInClickListenerandsetOnZoomOutClickListenereventsfor
implementingzoominandzoomoutfunctionality.Afterzoominandzoomoutthe
ZoomControlsisautomaticallyhidefromthescreenandre-shownifuserclickontheimage.A
Toastisdisplayedtoshowthezoominandzoomoutmessageonthescreen.
BelowyoucandownloadcompleteAndroidStudioprojectcode,finaloutputandstepbystep
explanationoftheexample:
Step1:C
reateanewprojectandnameitZoomControlsExample.
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepweaddthecodefordisplayingaImageViewandZoomControls.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
340
<RelativeLayout x
mlns:android ="
http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:layout_width ="
match_parent"
android:layout_height ="match_parent"
android:background ="
#000"
android:paddingBottom ="@dimen/activity_vertical_margin"
android:paddingLeft ="@dimen/activity_horizontal_margin"
android:paddingRight ="
@dimen/activity_horizontal_margin"
android:paddingTop ="
@dimen/activity_vertical_margin"
tools:context="
.MainActivity" >
<ImageView
android:id
="@+id/image"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_centerInParent ="
true"
android:src
="@drawable/image" /
>
<ZoomControls
android:id
="@+id/simpleZoomControl"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_alignParentBottom ="true"
android:layout_centerHorizontal ="
true"
android:layout_marginTop ="
50dp"/
>
</RelativeLayout>
Step3:O
pensrc->package->MainActivity.java
InthisstepfirstlyweinitiatetheImageViewandZoomControlsandthenhidethe
ZoomControlsfromthescreenandshowitonthetoucheventofimage.
WealsoperformsetOnZoomInClickListenerandsetOnZoomOutClickListenereventsfor
implementingzoominandzoomoutfunctionality.Afterzoominandzoomoutthe
ZoomControlsisautomaticallyhidefromthescreenandforre-showingituserneedtoclickon
image.AToastisdisplayedtoshowthezoominandzoomoutmessageonthescreen.
package
example.abhiandroid .z
oomcontrolsexample ;
import
android .o
s.B
undle;
import
android .s
upport .v
7.a
pp.AppCompatActivity;
import
android .v
iew .M
enu;
import
android .v
iew .M
enuItem ;
import
android .v
iew .M
otionEvent ;
import
android .v
iew .V
iew;
import
android .w
idget .B
utton ;
import
android .w
idget .I
mageView ;
import
android .w
idget .T
oast ;
import
android .w
idget .Z
oomControls ;
public
c
lassM
ainActivity extends A
ppCompatActivity
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
341
mageView
I image;
ZoomControls
simpleZoomControls ;
@Override
protected
void
onCreate (Bundle
savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.l
ayout .a
ctivity_main );
i
mage= (
I
mageView )findViewById (R.
id.i
mage );/
/ initiate a ImageView
s
impleZoomControls= (ZoomControls ) findViewById (R.i
d.simpleZoomControl );//
initiate a
ZoomControls
s
impleZoomControls .h
ide ();/
/ initially hide ZoomControls fromthescreen
//
perform setOnTouchListener event onImageView
i
mage .setOnTouchListener (newV
iew.OnTouchListener (){
@Override
public b
oolean
onTouch (V
iew
v,MotionEvent event ){
//
show Zoom Controls ontouch of image
s
impleZoomControls .s
how ();
return
f
alse ;
}
});
//
perform setOnZoomInClickListener event onZoomControls
s
impleZoomControls .s
etOnZoomInClickListener (newV
iew .O
nClickListener () {
@Override
public v
oid onClick (View
v){
//
calculate current scale xand y value ofImageView
float
x=image .g
etScaleX ();
float
y=image .g
etScaleY ();
//
set increased value ofscale x
and y
toperform zoomin
functionality
i
mage .setScaleX ((float )(
x+1)
);
i
mage .setScaleY ((float )(
y+1)
);
//
display a
toast to show Zoom In Message on Screen
Toast
.makeText (g
etApplicationContext (),"Zoom In",T
oast .L
ENGTH_SHORT ).show
();
//
hide the ZoomControls from the screen
s
impleZoomControls .h
ide ();
}
});
//
perform setOnZoomOutClickListener event onZoomControls
s
impleZoomControls .s
etOnZoomOutClickListener (n
ewView .OnClickListener (){
@Override
public v
oid onClick (View
v){
//
calculate current scale xand y value ofImageView
float
x=image .g
etScaleX ();
float
y=image .g
etScaleY ();
//
set decreased value ofscale x
and y
toperform zoomoutfunctionality
i
mage .setScaleX ((float )(
x-1)
);
i
mage .setScaleY ((float )(
y-1)
);
//
display a
toast to show Zoom Out Message onScreen
Toast
.makeText (g
etApplicationContext (),"Zoom
Out"
,Toast.L
ENGTH_SHORT ).show ();
//
hide the ZoomControls from the screen
s
impleZoomControls .h
ide ();
}
});
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
342
Output:
NowruntheAppandyoucanseeaimageonthescreen.ClickontheimageandZoomControls
buttonwillappearonthescreen.NowdoZoomInorZoomOuttheimageasyouwish.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
343
VideoView
InAndroid,VideoViewisusedtodisplayavideofile.Itcanloadimagesfromvarioussources
(suchascontentprovidersorresources)takingcareofcomputingitsmeasurementfromthe
videosothatitcanbeusedforanylayoutmanager,providingdisplayoptionssuchasscaling
andtinting.
ImportantNote:VideoViewdoesnotretainitsfullstatewhengoingintothebackground.In
particularitdoesnotrestorethecurrentplaypositionandplaystate.Applicationsshouldsave
andrestoretheseinonSaveInstanceState(Bundle)andonRestoreInstanceState(Bundle).
VideoViewcodeInXMLAndroid:
<VideoView
android:id
="@+id/simpleVideoView"
android:layout_width="
fill_parent"
android:layout_height="fill_parent" /
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
344
MethodsUsedinVideoView:
Let’swediscusssomeimportantmethodsofVideoViewthatmaybecalledinordertomanage
theplaybackofvideo:
1.setVideoUri(Uriuri):Thismethodisusedtosettheabsolutepathofthevideofilewhich
isgoingtobeplayed.ThismethodtakesaUriobjectasanargument.
BelowwesettheuriofvideowhichissavedinAndroidStudio:
Step1:Createanewdirectoryinresfolderandnameitraw
Step2:Saveavideonamefishvideoinrawfolder
Step3:NowusethebelowcodetosetthepathforthevideousingsetVideoUri()methodin
VideoView.
//initiate
a
videoview
VideoView
simpleVideoView=(V
ideoView)
findViewById
(R
.i
d
.s
impleVideoView
);
simpleVideoView.setVideoURI
(U
ri.p
arse
("
android.resource://" +
getPackageName
()
+
"
/"
+
R
.r
aw.f
ishvideo
));
SettingVideoFromOnlineWebSource:
Step1:FirstaddinternetpermisioninManifest.xmlfile.Wewillneedtoaddthissoasto
accessthevideothroughInternet.OpenAndroidManifest.xmlandaddthebelowcode
<!--Add
this
before
applicationtag
in
AndroidManifest.xml-->
<uses-permission
a
ndroid:name
="android.permission.INTERNET"
/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
345
Step2:AddthebasicVideoVideoXMLcodeinactivity_main.xmloractivity.xml
Step3:UsethebelowcodetoaccesstheVideofromourwebsite
packageabhiandroid .c
om .v
ideofromwebsource ;
import
android .a
pp.ProgressDialog ;
import
android .n
et.Uri;
import
android .s
upport .v7
.app.AppCompatActivity ;
import
android .o
s.B
undle ;
import
android .w
idget .VideoView ;
publicc
lass MainActivity e
xtends A
ppCompatActivity {
@Override
protected
voidonCreate (B
undle
savedInstanceState ){
super.onCreate (savedInstanceState );
setContentView (R.
layout .a
ctivity_main );
Uri
uri=
Uri
.p
arse ("http://abhiandroid.jobxfryqt.netdna-cdn.com/ui/wp-content/uploads/2016/04/videovi
ewtestingvideo.mp4" );
VideoView simpleVideoView= (V
ideoView )findViewById
(R
.i
d
.s
impleVideoView
);
/
/
initiate a
video view
simpleVideoView .s
etVideoURI (u
ri);
simpleVideoView .s
tart ();
}
}
2.setMediaController(MediaControllercontroller):T
hismethodofVideoViewisused
tosetthecontrollerforthecontrolsofvideoplayback.
Belowweshowhowtosetthemediacontrollerobjectforavideoview.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
346
//
createan
objectof
mediacontroller
MediaController
mediaController=n
ewMediaController
(this);
//
initiatea
videoview
VideoView
simpleVideoView= (
VideoView )
findViewById
(R.
id
.s
impleVideoView
);
//
set
mediacontrollerobjectfora
video
view
simpleVideoView.setMediaController(mediaController);
3.start():T
hismethodofVideoViewisusedtostarttheplaybackofvideofile.
Belowweshowhowtostartavideoinvideoview
VideoView
simpleVideoView=(
VideoView
)
findViewById
(R
.i
d
.s
impleVideoView
);
/
/
initiate
a
video
view
simpleVideoView
.s
tart
();
/
/starta
video
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
347
4.pause():Thismethodofvideoviewisusedtopausethecurrentplayback.
Belowweshowshowtopauseavideoinvideoview.
VideoView
simpleVideoView=(
VideoView
)
findViewById
(R
.i
d
.s
impleVideoView
);
/
/
initiate
a
video
view
simpleVideoView
.p
ause
();
/
/pausea
video
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
348
5.canPause():ThismethodwilltellwhetherVideoViewisabletopausethevideo.This
methodreturnsaBooleanvaluemeanseithertrueorfalse.Ifavideocanbepausedthenit
returnstrueotherwiseitreturnsfalse.
Belowwecheckswhetheravideoisabletopauseornot.
VideoViewsimpleVideoView=(VideoView)findViewById(R.id.simpleVideoView);//initiatea
videoview
BooleancanPauseVideo=simpleVideoView.canPause();//checkwhetheravideoisableto
pauseornot
6.canSeekForward():T
hismethodwilltellwhethervideoisabletoseekforward.This
methodreturnsaBooleanvaluei.e.trueorfalse.Ifavideocanseekforwardthenitreturnstrue
otherwiseitreturnsfalse.
Belowwecheckswhetheravideoisabletoseekforward ornot.
VideoView
simpleVideoView=(
VideoView
)
findViewById(R
.i
d
.s
impleVideoView);
/
/initiatea
video
view
Boolean
canSeekForward=
simpleVideoView .canSeekForward();/
/
checks
whethera
video
viewis
able
toseekforward o
r
not
7.canSeekBackward():T
hismethodwilltellwhethervideoisabletoseekbackward.This
methodreturnsaBooleanvaluei.e.trueorfalse.Ifavideocanseekbackwardthenitreturn
trueotherwiseitreturnfalse.
Belowwecheckswhetheravideoisabletoseekbackward ornot.
VideoView
simpleVideoView=(
VideoView
)
findViewById(R
.i
d
.s
impleVideoView
);
/
/
initiate
a
video
view
Boolean
canSeekBackword=
simpleVideoView .c
anSeekBackward();
/
/
checks
whether
a
video
view
is
ableto seek
backword
or
not
8.getDuration():T
hismethodisusedtogetthetotaldurationofVideoView.Thismethods
returnanintegervalue.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
349
Belowwegetthetotaldurationofa videoview.
VideoView
simpleVideoView=(
VideoView
)
findViewById(R
.i
d
.s
impleVideoView
);
/
/initiate
a
video
view
int
duration=
simpleVideoView
.getDuration
();
//
get
the total
duration
of
thevideo
9.getCurrentPosition():T
hismethodisusedtogetthecurrentpositionofplayback.This
methodreturnsanintegervalue.
Belowwegetthecurrentpositionofaplayback.
10.isPlaying():T
hismethodtellswhetheravideoiscurrentlyplayingornot.Thismethod
returnsaBooleanvalue.Itreturnstrueifvideoisplayingorfalseifit’snot.
Belowwecheckwhetheravideoviewiscurrentlyplayingornot
VideoView
simpleVideoView=
(
VideoView
)
findViewById
(R.
id
.s
impleVideoView
);/
/
initiate
a
video
view
Boolean
isPlaying=
simpleVideoView.i
sPlaying
();
/
/
check whether
a
videoview
is
currently
playingor not
11.stopPlayback():T
hismethodofVideoViewisusedtostopthevideoplayback.
Belowweshowhowtostopavideoinvideoview.
VideoView
simpleVideoView=
(
VideoView
)
findViewById
(R
.i
d
.s
impleVideoView
);
/
/
initiate
a
video
view
simpleVideoView
.s
topPlayback
();/
/
stop
a
video
12.setOnPreparedListener(MediaPlayer.OnPreparedListener):Thisisa listener
whichallowsacallbackmethodtobecalledwhenthevideoisreadytoplay.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
350
BelowweshowtheuseofsetOnPreparedListenereventofavideoview.
VideoView
simpleVideoView=
(V
ideoView )findViewById(R
.i
d
.s
impleVideoView
);
//
initiate
a
video
view
//
performset
on
preparedlistener event on
video
view
simpleVideoView.s
etOnPreparedListener (n
ewMediaPlayer
.O
nPreparedListener()
{
@Override
public
v
oid
onPrepared
(M
ediaPlayer
mp){
//
do
somethingwhen
videoisreadytoplay
}
});
13.setOnErrorListener(MediaPlayer.OnErrorListener):T
hislistenerallowsacallback
methodtobecalledwhenanerroroccursduringthevideoplayback.
BelowweshowtheuseofsetOnErrorListenereventofavideoview.
VideoView
simpleVideoView= (
VideoView)findViewById (R
.i
d.s
impleVideoView );
/
/
initiate
a
video
view
//
performsetonerrorlistenereventonvideoview
simpleVideoView .setOnErrorListener (n
ewM
ediaPlayer .O
nErrorListener ()
{
@Override
public
b
oolean
onError(M
ediaPlayer
mp
,int
what
,int
extra ){
//
do
something when
anerroris
occurduringthevideo playback
return
f
alse;
}
});
14.setOnCompletionListener(MediaPlayer.OnCompletionListener):T
hislistener
allowacallbackmethodtobecalledwhentheendofthevideoisreached.
BelowweshowstheuseofsetOnCompletionListenereventofavideoview.
VideoView
simpleVideoView=(
VideoView
)
findViewById(R
.i
d.s
impleVideoView
);
/
/initiate
a
video
view
//
performset
on
completionlistener
eventon
video
view
simpleVideoView.s
etOnCompletionListener(n
ew
M
ediaPlayer .O
nCompletionListener ()
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
351
@Override
public
v
oid
onCompletion
(M
ediaPlayer
mp
){
//
do
something
when
theend
of
the
videois
reached
}
});
MediaControllerInVideoView
MediaControllerisaclasswhichisusedtoprovidethecontrolsforthevideoplayback.Ifavideo
issimplyplayedusingtheVideoViewclassthentheuserwillnotbegivenanycontroloverthe
playbackofthevideowhichwillrununtiltheendofthevideoisreached.Thisissuecanbe
addressedbyattachinganinstanceoftheMediaControllerclasstotheVideoViewinstance.The
MediaControllerwillthenprovideasetofcontrolsallowingtheusertomanagetheplayback
(suchasseekingbackwards/forwardsandpausinginthevideotimeline).
MethodsOfMediaController:
Let’swediscusssomeimportantmethodsofMediaControllerclassthatmaybecalledinorder
tocontrolfortheplayback.
1.setAnchorView(Viewview):setAnchorViewisusedtodesignatestheviewtowhichthe
controlleristobeanchored.Thiscontrolsthelocationofthecontrolsonthescreen.
Belowweshowhowtousesetanchorview()methodofaMediaControllerclass.
MediaController
mediaController=
n
ew
M
ediaController
(t
his);
/
/create
an
object
of
media
controller
mediaController
.s
etAnchorView
(s
impleVideoView
);
/
/
setanchorview
for
video
view
2.show():Thismethodisusedtoshowthecontrolleronthescreen.
Belowweshowthecontrolleronthescreen.
MediaControllermediaController=newMediaController(this);//createanobjectofmedia
controller
mediaController.show();//showthecontrolleronthescreen
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
352
3.show(inttimeout):Thismethodisusedtosetthetimetoshowthecontrolleronthe
screen.
Belowwesetthetimeforshowingthecontrolleronthescreen.
4.hide():T
hismethodisusedtohidethecontrolsfromthescreen.
Belowwehidethecontrolfromthescreen
MediaController
mediaController=
n
ewM
ediaController
(t
his
);/
/
create
an
object
of
media
controller
mediaController
.h
ide
();
/
/
hide
the
controlfrom
the
screen
5.isShowing():ThismethodreturnsaBooleanvalueindicatingwhetherthecontrolsare
currentlyvisibletotheuserornot.
Belowwecheckswhetherthecontrolsarecurrentlyvisibleornot.
MediaController
mediaController=
n
ewM
ediaController
(t
his
);/
/
create
an
object
of
media
controller
Boolean
isShowing=
mediaController
.i
sShowing();
/
/
checkswhether
the
controls
are
currently
visible
ornot
VideoViewExampleInAndroidStudio:
BelowistheexampleofVideoViewinAndroidinwhichweplayavideoinavideoviewbyusing
MediaControllerandperformsetonerrorandcompletionlistenereventsanddisplayToast
whenthevideoiscompletedoranerroroccurwhileplayingtheevideo.
Inthisexamplewecreateafoldernamedrawinourprojectandstorethevideofileinthat
folderandthensettheuriforthevideoinouractivityinwhichwedisplaythevideoview.
Belowisthefinaloutput,downloadcodeandstepbystepexplanation:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
353
Step1:C
reateanewprojectinAndroidStudioandnameitVideoViewExample
Step2:O
penres->layout->xml(or)main.xmlandaddfollowingcode:
InthisstepweopenanxmlfileandaddthecodetodisplayaVideoViewinouractivity.
<RelativeLayoutx
mlns:android ="
http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
=".MainActivity" >
<VideoView
android:id
="@+id/simpleVideoView"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"/
>
</RelativeLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
354
Step3:O
pensrc->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodetoinitiatethevideoviewandcreatean
objectofMediaControllertocontrolthevideoplayback.
Inthisclasswealsosettheuriforthevideoandperformsetonerrorandcompletionlistener
eventsanddisplayToastmessagewhenvideoiscompletedoranerrorisoccurwhileplaying
theevideo.
Alsomakesuretocreateanewdirectoryinresfolderandnameitraw.Saveavideoname
fishvideoinrawfolder.WewillbesettingpathtothisVideoinsetVideoURI()method.
package
example .a
bhiandroid .v
ideoviewexample ;
import
android .app
.Activity ;
import
android .app
.ProgressDialog ;
import
android .content .r
es.Configuration ;
import
android .media.MediaPlayer ;
import
android .media.MediaPlayer .O
nPreparedListener ;
import
android .net
.Uri;
import
android .os
.B
undle ;
import
android .util.L
og;
import
android .view.M
enu ;
import
android .view.M
enuItem ;
import
android .view.V
iew ;
import
android .widget.MediaController ;
import
android .widget.Toast ;
import
android .widget.VideoView ;
public
c
lass MainActivity extends Activity {
VideoView
simpleVideoView ;
MediaController
mediaControls ;
@Override
protected
v
oid
onCreate (Bundle
savedInstanceState ){
super
.o
nCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .activity_main );
//
Find your VideoView inyour video_main.xml layout
s
impleVideoView= (V
ideoView )
findViewById (R
.i
d.s
impleVideoView );
if
(
m
ediaControls= =
null){
//create anobject ofmedia controller class
m
ediaControls= new
MediaController (M
ainActivity .t
his
);
m
ediaControls .setAnchorView (s
impleVideoView );
}
//
set themedia controller forvideo view
s
impleVideoView .setMediaController (m
ediaControls );
//
set theurifor the video view
s
impleVideoView .setVideoURI (Uri
.parse ("
android.resource://" +
getPackageName
()
+
"
/"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
355
+
R.
raw.f
ishvideo ));
//
start a
video
s
impleVideoView .start();
//
implement on completion listener on
video view
s
impleVideoView .setOnCompletionListener (new
MediaPlayer .O
nCompletionListener ()
{
@Override
publicv
oid onCompletion (M
ediaPlayer
mp
){
Toast
.makeText (g
etApplicationContext (), "
Thank You...!!!" ,
Toast .LENGTH_LONG ).
show ();/
/display a
toast whenan video is
completed
}
});
s
impleVideoView .setOnErrorListener (n
ewM
ediaPlayer .O
nErrorListener ()
{
@Override
publicb
oolean
onError (M
ediaPlayer
mp,i
ntwhat ,int
extra){
Toast
.makeText (g
etApplicationContext (), "
Oops AnError
Occur While
Playing
Video...!!!" ,Toast
.LENGTH_LONG ).
show ();
/
/display a
toast whenan
errorisoccured
while
playing an
video
return
f
alse ;
}
});
}
}
Output:
NowruntheAppandyouwillseeVideoplayingastheAppopen.ClickontheVideoandMedia
Controllerwillappearonthescreen.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
356
SearchView
InAndroid,SearchViewwidgetprovidesearchuserinterfacewhereuserscanenterasearch
queryandthensubmitarequesttosearchprovider.Itshowsalistofquerysuggestionsor
resultsifavailableandallowtheuserstopickasuggestionorresulttolaunchinto.
BasicSearchViewcodeinXML:
<SearchView
android:id
="
@+id/simpleSearchView"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content" /
>
SearchViewMethodsInAndroid:
Let’swediscusssomeimportantmethodsofsearchviewthatmaybecalledinordertomanage
thesearchview.
1.getQuery():T
hisfunctionisusedtogetthequerystringcurrentlyinthetextfieldofa
searchview.ThismethodreturnsCharSequencetypevalue.
BelowwegetthequeryStringfromasearchview.
SearchViewsimpleSearchView=(SearchView)findViewById(R.id.simpleSearchView);//
inititateasearchview
CharSequencequery=simpleSearchView.getQuery();//getthequerystringcurrentlyinthe
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
357
textfield
2.getQueryHint():Thisfunctionisusedforgettingthehinttextthatwillbedisplayedinthe
querytextfield.ThismethodreturnsaCharSequencetypevalue.
Belowisanexamplecodewhichgetthehinttextthatwillbedisplayedinthequerytextfieldof
asearchview.
SearchView
simpleSearchView=(
SearchView
)findViewById
(R
.i
d
.s
impleSearchView);
/
/
inititate
a
search
view
CharSequence
queryHint=
simpleSearchView.getQueryHint
();/
/get
the
hint
text
thatwill
be
displayed
inthe
query
text
field
3.isIconfiedByDefault():Thismethodreturnsthedefaulticonifiedstateofthesearchfield.
ThismethodreturnsaBooleanvalueeithertrueorfalse.
Belowwegetthedefaultstateofthesearchfield.
SearchView
simpleSearchView=(
SearchView
)
findViewById
(R
.i
d.s
impleSearchView);
/
/
inititate
a
searchview
boolean
isIconfied =s
impleSearchView.i
sIconfiedByDefault
();//checks
default
iconified
state
of
the
search field
4.setIconifiedByDefault(Booleaniconify):Thismethodisusedtosetthedefaultor
restingstateofthesearchfield.InthismethodwesetBooleanvaluetrueorfalse.
ImportantNote:W
henaSearchViewisusedinanActionBarasanactionviewforcollapsible
menuitemthenitneedstobesettoiconifiedbydefaultusingsetIconfiedByDefault(true)
function.Ifyouwantthesearchfieldtoalwaysbevisible,thencallsetIconifiedByDefault(false).
trueisthedefaultvalueforthisfunction.Youcanalsoseticonfiedfromxmlbyusing
iconfiedByDefaultpropertytotrueorfalse.
Belowwesettheiconifiedbydefaultvaluetofalse.
SearchView
simpleSearchView=
(
SearchView
)
findViewById(R
.i
d.s
impleSearchView
);/
/
inititate
a
search
view
simpleSearchView
.s
etIconifiedByDefault(f
alse);
/
/
set
the default
or
restingstateof
the
search
field
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
358
5.setQueryHint(CharSequencehint):T
hismethodisusedtosetthehinttexttodisplay
inthequerytextfield.ThismethodsupportCharSequencetypevalue.
BelowwesetthequeryhintforaSearchView.
SearchView
simpleSearchView=
(S
earchView
)
findViewById
(R
.i
d
.s
impleSearchView);
/
/inititate
a
search
view
simpleSearchView.s
etQueryHint("
Search
View"
);
/
/
set
thehinttext
to
display
inthe
query
text
field
6.setOnQueryTextFocusChangeListener(OnFocusChangeListenerlistener):This
listenerinformwhenthefocusofthequerytextfieldchanges.
InthebelowcodeweshowtheuseofsetOnQueryTextFocusChangeListener()ofSearchView.
SearchView
simpleSearchView= (
SearchView)findViewById (R
.i
d.s
impleSearchView
);
/
/inititate
asearch
view
//performsetonquery
text
focus change
listenerevent
simpleSearchView .s
etOnQueryTextFocusChangeListener (n
ewView .O
nFocusChangeListener()
{
@Override
publicv
oid
onFocusChange (V
iew
v,
b
oolean
hasFocus){
//do
something whenthe
focusof
thequerytext
field changes
}
});
7.setOnQueryTextListener(OnQueryTextListenerlistener):Itisauseractionwithin
theSearchView.
BelowweshowtheuseofsetOnQueryTextListener()ofsearchview.
SearchView
simpleSearchView= (
SearchView)
findViewById(R.
id
.s
impleSearchView
);/
/
inititate
asearch
view
//performseton query
text
listenerevent
simpleSearchView .s
etOnQueryTextListener (new
SearchView
.O
nQueryTextListener ()
{
@Override
publicb
oolean
onQueryTextSubmit (S
tring
query ){
//do
something ontext
submit
returnf
alse;
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
359
@Override
public
b
oolean
onQueryTextChange(S
tring
newText
){
//
do
something when
text
changes
return
f
alse
;
}
});
AttributesofSearchView:
Nowlet’swediscusssomecommonattributesofasearchviewthathelpsustoconfigureitin
ourlayout(xml).
1.Id:idattributeisusedtouniquelyidentifyasearchview.
<!-- i
d
ofan
searchview
used
touniquely
identify
it
-->
<SearchView
android:id
="
@+id/simpleSearchView"
android:layout_width="
wrap_content"
android:layout_height="wrap_content" /
>
2.queryHint:T
hisattributeiausedtosetoptionalqueryhintstringwhichwillbedisplayed
intheemptyqueryfield.Queryhintissameashintattributeforedittext.
Belowwesetthequeryhintofansearchview.
<SearchView
android:id
="
@+id/simpleSearchView"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:iconifiedByDefault
="
false"
android:queryHint
="
SearchHere"
/
>
<!--
set
query
string
of
an
search
view
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
360
3.iconifiedByDefault:T
hisattributeofsearchviewisusedtosetthedefaultorrestingstate
ofthesearchfield.YoucansetaBooleanvalueforthisattributeanddefaultvalueistrue.True
valueindicatesyoucaniconifiesorexpandsthesearchview.
Belowwesetthefalsevalueforthisattribute.
<SearchView
android:id="@+id/simpleSearchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Searchhere"/><!--seticonifiedbydefaulttofalse-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
361
4.background:backgroundattributeisusedtosetthebackgroundofasearchview.Youcan
setacolororadrawableinthebackgroundofasearchview.Youcanalsosetthebackground
colorinjavaclass.
Belowwesettheredcolorforthebackgroundofasearchview.
<SearchView
android:id
="
@+id/simpleSearchView"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:iconifiedByDefault
="
false"
android:queryHint
="
Search here"
android:background
="#f00"/>
<!--
redcolor
for
the
background
of
search
view
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
362
SettingbackgroundofSearchViewInJavaclass:
SearchView
simpleSearchView
=(
SearchView
)f
indViewById
(R.
id
.s
impleSearchView
);
simpleSearchView
.s
etBackgroundColor
(C
olor.R
ED
);
5.padding:p
addingattributeisusedtosetthepaddingfromleft,right,toporbottom.
paddingRight:s etthepaddingfromtherightsideofthesearchview.
paddingLeft:setthepaddingfromtheleftsideofthesearchview.
paddingTop:setthepaddingfromthetopsideofthesearchview.
paddingBottom:s etthepaddingfromthebottomsideofthesearchview
Padding:setthepaddingfromtheallside’softhesearchview.
Belowweset40dppaddingfromallthesidesofasearchview.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
363
<SearchView
android:id
="
@+id/simpleSearchView"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:iconifiedByDefault
="
false"
android:queryHint
="
Search View"
android:background
="#f00"
android:padding
="
40dp" /><
!--set
40dp
padding
from
all
the
sides
of
a
search
view
-->
SearchViewExampleInAndroidStudio:
InthebelowexampleofSearchViewwedisplaySearchViewandListView.Inthiswecreatean
animalnamelistandthensettheAdaptertofillthedatainListView.Finallyweimplement
SearchView.OnQueryTextListenertofiltertheanimallistaccordingtosearchquery.
BelowyoucandownloadcompleteSearchViewAndroidStudioprojectcode,seefinaloutput
andstepbystepexplanationofexample:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
364
Step1:CreateanewprojectandnameitSearchViewExample
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepweopenanxmlfileandaddthecodefordisplayingaSearchViewandListViewby
usingitsdifferentattributes.
<RelativeLayout
xmlns:android="
http://schemas.android.com/apk/res/android"
android:layout_width
="fill_parent"
android:layout_height
="
fill_parent" >
<SearchView
android:id
="
@+id/search"
android:layout_width
="
fill_parent"
android:layout_height
="wrap_content"
android:iconifiedByDefault
="false"
>
<requestFocus
/
>
</SearchView>
<ListView
android:id
="
@+id/listview"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
365
ndroid:layout_width
a ="fill_parent"
android:layout_height
="fill_parent"
android:layout_below
="@+id/search"
/>
</RelativeLayout>
Step3:Open src->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodetoinitiateSearchViewandListView.Inthis
wecreateanAnimalnamelistandthensettheadaptertofillthedatainListView.Inthiswe
alsoimplementSearchView.OnQueryTextListenertofiltertheanimallistaccordingtosearch
query.
package
example .abhiandroid .searchviewexample ;
import
android .o
s.B
undle ;
import
android .s
upport .v
7.app.A
ppCompatActivity ;
import
android .w
idget .ListView ;
import
android .w
idget .SearchView ;
import
java .u
til .ArrayList ;
public
c
lass MainActivity extends A
ppCompatActivity i
mplements
SearchView .O
nQueryTextListener {
//
Declare Variables
ListView
list;
ListViewAdapter
adapter ;
SearchView
editsearch ;
String
[]
animalNameList ;
ArrayList
<AnimalNames >arraylist= newArrayList <AnimalNames >();
@Override
public
v
oid onCreate (Bundle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .activity_main );
//
Generate sample data
a
nimalNameList= newS
tring []{
"Lion" ,"Tiger" ,"
Dog" ,
"Cat"
,"Tortoise" ,"Rat" ,"Elephant" ,"Fox" ,
"Cow"
,"
Donkey" ,"
Monkey" };
//
Locate the ListView in listview_main.xml
l
ist= (
ListView )findViewById (R.i
d.l
istview );
for
(
inti=
0;i<
animalNameList .length;i+
+){
AnimalNames
animalNames= n
ew AnimalNames (a
nimalNameList [i]
);
//Binds all strings intoan array
a
rraylist .a
dd(animalNames );
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
366
/
/ Pass
results
to
ListViewAdapterClass
a
dapter=
n
ew
L
istViewAdapter
(t
his
,arraylist
);
/
/ Bindsthe
Adapter
tothe
ListView
l
ist.s
etAdapter
(a
dapter
);
/
/ Locate
the EditText
in
listview_main.xml
e
ditsearch=(
SearchView
)
findViewById
(R
.i
d
.s
earch
);
e
ditsearch
.s
etOnQueryTextListener (t
his
);
}
Override
@
public
b
oolean
onQueryTextSubmit
(S
tring
query
){
return
f
alse
;
}
Override
@
public
b
oolean
onQueryTextChange
(S
tring
newText
){
String
text= newText
;
a
dapter.filter(text
);
return
f
alse ;
}
}
Step4:NowcreateNewClass.Gotoapp->java->rightclickonpackage->New->JavaClass
andcreateListViewAdapter.javaandaddfollowingcode.HereweextendsBaseAdapterin
ListViewAdapterclassandthensetthedataintheListViewbyusingModalclass.
package
example.abhiandroid .searchviewexample ;
import
android .c
ontent .C
ontext ;
import
android .v
iew.L
ayoutInflater ;
import
android .v
iew.V
iew ;
import
android .v
iew.V
iewGroup ;
import
android .w
idget.BaseAdapter ;
import
android .w
idget.TextView ;
import
java.u
til.ArrayList ;
import
java.u
til.List
;
import
java.u
til.Locale;
public
c
lassL
istViewAdapter e
xtends B
aseAdapter
{
//
Declare Variables
Context
mContext ;
LayoutInflater
inflater ;
private
L
ist<AnimalNames > animalNamesList=n
ull ;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
367
private
A
rrayList
<A
nimalNames
>
arraylist
;
public
L
istViewAdapter(Context
context
,L
ist<A
nimalNames
>
animalNamesList
){
m
Context=
context;
this
.a
nimalNamesList=animalNamesList;
i
nflater=L
ayoutInflater .f
rom
(m
Context);
this
.a
rraylist=
n
ewA
rrayList<A
nimalNames>();
this
.a
rraylist
.a
ddAll(animalNamesList);
}
public
c
lass
V
iewHolder
{
TextView
name
;
}
Override
@
public
i
nt
getCount
()
{
return
animalNamesList.s
ize
();
}
Override
@
public
A
nimalNames
getItem
(i
nt
position
){
return
animalNamesList
.get
(p
osition
);
}
Override
@
public
l
ong
getItemId
(i
nt
position
){
return
position
;
}
public
V
iewgetView (f
inal i
nt
position ,V
iewview
,ViewGroup
parent
){
final
V
iewHolder holder;
if
(
v
iew= =
n
ull ){
h
older=newV
iewHolder ();
v
iew=
inflater .inflate (R
.l
ayout.listview_item ,n
ull
);
//Locate theTextViews in listview_item.xml
h
older.n
ame= (T
extView )view.f
indViewById (R
.i
d
.n
ame
);
v
iew.s
etTag (h
older );
}e
lse{
h
older=(V
iewHolder )view .getTag
();
}
//
Set the
results intoTextViews
h
older .n
ame.setText (animalNamesList .g
et(p
osition ).getAnimalName
());
return
view
;
}
/
/ Filter Class
public
v
oidfilter (S
tring
charText ){
charText=
charText .t
oLowerCase (L
ocale.g
etDefault
());
animalNamesList .c
lear
();
if
(
c
harText .length()
=
=
0
){
a
nimalNamesList .a
ddAll(a
rraylist );
}e
lse{
for
(A
nimalNames
wp:
arraylist ){
if
(
wp
.g
etAnimalName (). toLowerCase(L
ocale
.g
etDefault
()).
contains
(c
harText
))
{
a
nimalNamesList
.a
dd
(w
p
);
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
368
}
n
otifyDataSetChanged
();
}
}
Step5:N
owCreatenewanewlayoutActivity.Gotores->rightclickonlayout->New->
Activity->BlankActivityandcreatelist_view_items.xmlandaddfollowingcode.Hereweare
creatingitemsviewthatwillbedisplayedinsideeachrow.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView
android:id="@+id/nameLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Animal:"/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/nameLabel"/>
</RelativeLayout>
Step6:N
owcreateNewClass.Gotoapp->java->rightclickonpackage->New->JavaClass
andcreateAnimalNames.javaandaddfollowingcode.Herewehaveaconstructorforsetting
theanimalnameandafunctiontogettheanimalname.
packageexample.a
bhiandroid .searchviewexample ;
publicc
lassAnimalNames{
private
S
tring
animalName ;
public
A
nimalNames(S
tring
animalName
){
this
.a
nimalName=animalName;
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
369
public
S
tring
getAnimalName()
{
return
t
his.a
nimalName
;
}
}
Output:
NowruntheApp,youwillseedifferentAnimalnameslisted.NowtypefirstcharacterofAnimal
thatcametoyourmindinSearchViewandyouwillthelistissorted.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
370
Toast
InAndroid,Toastisusedtodisplayinformationforaperiodoftime.Itcontainsamessagetobe
displayedquicklyanddisappearsafterspecifiedperiodoftime.Itdoesnotblocktheuser
interaction.ToastisasubclassofObjectclass.Inthisweusetwoconstantsforsettingthe
durationfortheToast.Toastnotificationinandroidalwaysappearsnearthebottomofthe
screen.Wecanalsocreateourcustomtoastbyusingcustomlayout(xmlfile).
SpecialNote:I nAndroid,Toastisusedwhenwerequiredtonotifyuseraboutanoperation
withoutexpectinganyuserinput.Itdisplaysasmallpopupformessageandautomaticallyfades
outaftertimeout.
ImportantMethodsOfToast:
Let’swediscusssomeimportantmethodsofToastthatmaybecalledinordertomanagethe
Toast.
1.makeText(Contextcontext,CharSequencetext,intduration):Thismethodisused
toinitiatetheToast.ThismethodtakethreeparametersFirstisfortheapplicationContext,
SecondistextmessageandlastoneisdurationfortheToast.
ConstantsofToast:BelowistheconstantsofToastthatareusedforsettingthedurationforthe
Toast.
1.LENGTH_LONG:ItisusedtodisplaytheToastforalongperiodoftime.Whenwesetthis
durationtheToastwillbedisplayedforalongduration.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
371
2.LENGTH_SHORT:ItisusedtodisplaytheToastforshortperiodoftime.Whenwesetthis
durationtheToastwillbedisplayedforshortduration.
BelowweshowtheuseofmakeText()methodofToastinwhichwesetapplicationcontext,a
textmessageanddurationfortheToast.
Toast
toast=
Toast
.m
akeText
(g
etApplicationContext
(),
"
SimpleToast"
,T
oast
.L
ENGTH_LONG
);
/
/
initiate
theToast
with
context,
message
and
durationfor
the
Toas
2.show():T
hismethodisusedtodisplaytheToastonthescreen.Thismethodisdisplaythe
textwhichwecreateusingmakeText()methodofToast.
BelowweFirstlyinitiatetheToastandthendisplayitusingshow()method.
Toast
toast=
Toast
.m
akeText
(g
etApplicationContext(),
"
Simple
Toast
In
Android"
,
Toast
.L
ENGTH_LONG);
/
/
initiatethe
Toast
with
context,
message
and
duration
forthe
Toast
toast
.s
how
();/
/
display
theToast
3.setGravity(int,int,int):T
hismethodisusedtosetthegravityfortheToast.Thismethod
acceptsthreeparameters:aGravityconstant,anx-positionoffset,anday-positionoffset.
BelowweFirstlyinitiatetheToast,settopandleftgravityandthendisplayitusingshow()
method.
Toast
toast=
Toast
.m
akeText
(g
etApplicationContext (),
"
Simple
ToastIn
Android"
,
Toast
.L
ENGTH_LONG);
/
/
initiatethe
Toast
withcontext,messageand
duration
forthe
Toast
toast
.s
etGravity(G
ravity
.T
OP
|Gravity
.L
EFT
,0
,0
);
/
/
set
gravityfor
the
Toast.
toast
.s
how
();/
/
display
theToast
4.setText(CharSequences):T
hismethodisusedtosetthetextfortheToast.Ifweuse
makeText()methodandthenwewanttochangethetextvaluefortheToastthenweusethis
method.
BelowwefirstlycreateanewToastusingmakeText()methodandthensetthetextfortheToast.
Toasttoast=Toast.makeText(getApplicationContext(),"SimpleToastInAndroid",
Toast.LENGTH_LONG);//initiatetheToastwithcontext,messageanddurationfortheToast
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
372
toast.setGravity(Gravity.TOP|Gravity.LEFT,0,0); //setgravityfortheToast.
toast.setText("ChangedToastText");//setthetextfortheToast
toast.show();//displaytheToast
5.setDuration(intduration):T
hismethodisusedtosetthedurationfortheToast.Ifwe
usemakeText()methodandthenwewanttochangethedurationfortheToastthenweusethis
method.
BelowwefirstlycreateanewToastusingmakeText()methodandthensetthedurationforthe
Toast.
Toast
toast=
Toast.m
akeText(g
etApplicationContext (),
"
Simple
ToastInAndroid"
,
Toast
.L
ENGTH_LONG);/
/
initiate the
Toast
withcontext,messageandduration
forthe
Toast
toast
.s
etGravity(G
ravity.TOP
|G
ravity.L
EFT
,0
,0
);
/
/
set
gravity for
the
Toast.
toast
.s
etDuration(Toast
.LENGTH_SHORT);
/
/
settheduration
forthe
Toast.
toast
.s
how
();/
/
display the
Toast
6.inflate(int,ViewGroup):T
hismethodisusedtoinflatethelayoutfromthexml.Inthis
methodfirstparameteristhelayoutresourceIDandthesecondistherootView.
BelowweretrievetheLayoutInflaterandtheninflatethelayoutfromthexmlfile.
//
Retrieve
theLayout
Inflater and
inflate
thelayout
from
xml
LayoutInflater
inflater=
getLayoutInflater ();
View
layout
=
inflater.i
nflate (R
.l
ayout
.c
ustom_toast_layout,
(
ViewGroup
)
findViewById(R.
id
.t
oast_layout_root ));
7.setView(View):ThismethodisusedtosettheviewfortheToast.Inthismethodwepass
theinflatedlayoutwhichweinflateusinginflate()method.
Belowwefirstlyretrievethelayoutinflaterandtheninflatethelayoutandfinallycreateanew
ToastandpasstheinflatedlayoutinthesetView()method.
//
Retrieve
the LayoutInflater andinflate thelayout
from
xml
LayoutInflaterinflater=getLayoutInflater ();
View
layout
=inflater.inflate (R
.l
ayout .c
ustom_toast_layout ,
(
ViewGroup
)
findViewById (R.
id
.t
oast_layout_root ));
//
create
a
new Toast
using context
Toast
toast=
newT
oast
(getApplicationContext ());
toast
.s
etDuration (T
oast.L
ENGTH_LONG );/
/settheduration
for
the
Toast
toast
.s
etView
(layout);
/
/ setthe inflated layout
toast
.s
how
();/
/display thecustom Toast
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
373
CustomToastinAndroid:
InAndroid,SometimessimpleToastmaynotbesatisfactory,andthenwecangofor
customizingaToast.Forcreatingacustomlayout,defineaViewlayout,inXMLandpassthe
rootViewobjecttothesetView(View)method.
StepsforImplementationofCustomToastInAndroid:
Step2:C
reateanewToastwithToast(Context)andsetsomepropertiesoftheToast,suchas
thedurationandgravity.
Step3:CallsetView(View)andpasstheinflatedlayoutinthismethod.
Step4:DisplaytheToastonthescreenusingshow()methodofToast.
InthebelowexamplewehaveshownthefunctioningofToastandcustomToastboth.
ToastAndCustomToastExampleInAndroidStudio:
BelowistheexampleofToastandCustomToastinAndroid.Inthisexamplewedisplaytwo
Button’soneforSimpleToastandotherforCustomToastandperformclickeventonthem.
WheneverauserclickonsimpleToastButtonaToastwithmessage“SimpleToastInAndroid”
displayedonthescreenandwhenauserclicksoncustomtoastButtonamessage“Custom
ToastInAndroid”withaimagedisplayedonthescreen.ForCreatingacustomtoastwefirstly
retrievethelayoutinflaterandtheninflatethecustomtoastlayoutfromthexmlfile.Afterthat
wegetthereferenceofTextViewandImageViewfromtheinflatedlayoutandsetthetextand
imageintheTextViewandImageView.FinallywecreateanewToastandpasstheinflated
layoutinthesetView()methodandthendisplaytheToastbyusingshow()methodofToast.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
374
Belowisthefinaloutput,downloadAndroidStudiocodeandstepbystepexplanationofthe
example:
Step1:C
reateanewprojectandnameitToastExample
Step2: O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
<RelativeLayout x
mlns:android ="
http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools"
android:layout_width ="
match_parent"
android:layout_height ="match_parent"
android:paddingBottom ="@dimen/activity_vertical_margin"
android:paddingLeft ="@dimen/activity_horizontal_margin"
android:paddingRight ="
@dimen/activity_horizontal_margin"
android:paddingTop ="
@dimen/activity_vertical_margin"
tools:context="
.MainActivity" >
<!--
Button'sforsimple and
customToast
-->
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
375
<Button
android:id
="
@+id/simpleToast"
android:layout_width ="
200dp"
android:layout_height ="wrap_content"
android:layout_centerHorizontal ="
true"
android:layout_marginTop ="150dp"
android:background="#f00"
android:text="
SimpleToast"
android:textColor="#fff"
android:textSize="
20sp" /
>
<Button
android:id
="
@+id/customToast"
android:layout_width ="
200dp"
android:layout_height ="wrap_content"
android:layout_below ="
@+id/simpleToast"
android:layout_centerHorizontal ="
true"
android:layout_margin ="50dp"
android:background="#0f0"
android:text="
CustomToast"
android:textColor="#fff"
android:textSize="
20sp" /
>
</RelativeLayout>
Step3: Nowcreateaxmllayoutsbyrightclickingonres/layout->New->LayoutResource
Fileandnameitcustom_toast_layout.xml
<LinearLayoutx
mlns:android ="http://schemas.android.com/apk/res/android"
android:id
="@+id/toast_layout_root"
android:layout_width ="
fill_parent"
android:layout_height ="fill_parent"
android:background ="
#DAAA"
android:orientation ="horizontal"
android:padding="8dp">
<!--
ImageVView andTextView forcustom
Toast
-->
<ImageView
android:id
="@+id/toastImageView"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_marginRight ="
8dp"/>
<TextView
android:id
="@+id/toastTextView"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:textColor ="
#FFF" /
>
</LinearLayout>
Step4:O
pen src->package->MainActivity.java
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
376
InthisstepweopenMainActivityandaddthecodeforinitiatetheButton’sandperformclick
eventonButton’s.WheneverauserclickonsimpleToastButtonaToastwithmessage“Simple
ToastInAndroid”displayedonthescreenandwhenauserclicksoncustomtoastButtona
message“CustomToastInAndroid”withaimagedisplayedonthescreen.ForCreatinga
customtoastwefirstlyretrievethelayoutinflaterandtheninflatethecustomtoastlayoutfrom
thexmlfile.AfterthatwegetthereferenceofTextViewandImageViewfromtheinflatedlayout
andsetthetextandimageintheTextViewandImageView.FinallywecreateanewToastand
passtheinflatedlayoutinthesetView()methodandthendisplaytheToastbyusingshow()
methodofToast.
package
com .a
bhiandroid .t
oastexample ;
import
android .s
upport .v7.a
pp.AppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .G
ravity ;
import
android .v
iew .L
ayoutInflater ;
import
android .v
iew .V
iew ;
import
android .w
idget .ImageView ;
import
android .w
idget .TextView ;
import
android .w
idget .Toast ;
import
android .w
idget .Button ;
import
android .v
iew .V
iewGroup ;
public
c
lass MainActivity extends A
ppCompatActivity {
Button
simpleToast , customToast ;
@Override
protected
voidonCreate (B
undle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.l
ayout .a
ctivity_main );
//
get the reference ofButton's
s
impleToast =( B
utton )findViewById (R.
id
.simpleToast );
c
ustomToast =( B
utton )findViewById (R.
id
.customToast );
//
perform setOnClickListener event onsimple ToastButton
s
impleToast .s
etOnClickListener (newV
iew .O
nClickListener ()
{
@Override
public void onClick (V
iew v)
{
//
initiate a
Toast with message and duration
Toast
toast= Toast .m
akeText (g
etApplicationContext (),"
SimpleToast In
Android",T oast .LENGTH_LONG );/
/initiate theToast with context, messageandduration for
the
Toast
t
oast .setGravity (Gravity .B
OTTOM| G
ravity .C
ENTER_HORIZONTAL ,0
,0
);
/
/
set
gravity for theToast.
t
oast .show ();/
/ display the Toast
}
});
//
perform setOnClickListener event oncustom ToastButton
c
ustomToast .s
etOnClickListener (newV
iew .O
nClickListener ()
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
377
@Override
publicv
oid
onClick (V
iew
v){
//
Retrieve theLayout Inflater and inflate thelayout
fromxml
LayoutInflater
inflater= getLayoutInflater ();
View
layout=
inflater .i
nflate (R.
layout .c
ustom_toast_layout ,
(V
iewGroup )
findViewById (R.i
d.t
oast_layout_root ));
//
get the reference ofTextView and ImageVIew from
inflated layout
TextView
toastTextView= (TextView ) layout .findViewById (R
.i
d
.toastTextView
);
ImageView
toastImageView= (I
mageView )
layout.f
indViewById (R.
id
.t
oastImageView );
//
set the textintheTextView
t
oastTextView .s
etText ("Custom Toast InAndroid" );
//
set the Image in
the ImageView
t
oastImageView .setImageResource (R.
drawable .i
c_launcher );
//
create a
newToast using context
Toast
toast= n
ewToast(getApplicationContext ());
t
oast.setDuration (Toast.LENGTH_LONG );/
/set thedurationforthe
Toast
t
oast.setView (l
ayout );/
/ set
the inflated layout
t
oast.show();/
/display thecustom Toast
}
});
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
378
IntentinAndroid
AndroidusesIntentforcommunicatingbetweenthecomponentsofanApplicationandalso
fromoneapplicationtoanotherapplication.
IntentaretheobjectswhichisusedinandroidforpassingtheinformationamongActivitiesin
anApplicationandfromoneapptoanotheralso.Intentareusedforcommunicatingbetween
theApplicationcomponentsanditalsoprovidestheconnectivitybetweentwoapps.
Forexample:Intentfacilitateyoutoredirectyouractivitytoanotheractivityonoccurrenceof
anyevent.Bycalling,startActivity()youcanperformthistask.
Intent
intent
=n
ew
I
ntent
(g
etApplicationContext
(),
S
econdActivity
.c
lass
);
startActivity
(i
ntent
);
Intheaboveexample,foregroundactivityisgettingredirectedtoanotheractivityi.e.
SecondActivity.java.getApplicationContext()returnsthecontextforyourforegroundactivity.
TypesofIntents:
Intentareoftwotypes:ExplicitIntentandImplicitIntent
ExplicitIntent:
ExplicitIntentsareusedtoconnecttheapplicationinternally.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
379
InExplicitweusethenameofcomponentwhichwillbeaffectedbyIntent.ForExample:Ifwe
knowclassnamethenwecannavigatetheappfromOneActivitytoanotheractivityusing
Intent.Inthesimilarwaywecanstartaservicetodownloadafileinbackgroundprocess.
ExplicitIntentworkinternallywithinanapplicationtoperformnavigationanddatatransfer.
ThebelowgivencodesnippetwillhelpyouunderstandtheconceptofExplicitIntents
Intent
intent
=n
ew
I
ntent
(g
etApplicationContext
(),
S
econdActivity
.c
lass
);
startActivity
(i
ntent
);
HereSecondActivityistheJAVAclassnamewheretheactivitywillnowbenavigated.Example
withcodeintheendofthispostwillmakeitmoreclear.
ImplicitIntent:
InImplicitIntentswedoneedtospecifythenameofthecomponent.WejustspecifytheAction
whichhastobeperformedandfurtherthisactionishandledbythecomponentofanother
application.
ThebasicexampleofimplicitIntentistoopenanywebpage
Let’stakeanexampletounderstandImplicitIntentsmoreclearly.Wehavetoopenawebsite
usingintentinyourapplication.Seethecodesnippetgivenbelow
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
380
Intent
intentObj=
new
Intent
(I
ntent
.A
CTION_VIEW
);
intentObj
.s
etData
(U
ri.p
arse("
http://www.abhiandroid.com"
));
startActivity
(i
ntentObj );
UnlikeExplicitIntentyoudonotuseanyclassnametopassthroughIntent().Inthisexample
wehasjustspecifiedanaction.NowwhenwewillrunthiscodethenAndroidwillautomatically
startyourwebbrowseranditwillopenAbhiAndroidhomepage.
IntentExampleInAndroid:
Let’simplementIntentforaverybasicuse.InthebelowexamplewewillNavigatefromone
ActivitytoanotherandopenawebhomepageofAbhiAndroidusingIntent.Theexamplewill
showyoubothimplicitandexplicitIntenttogether.Belowisthefinaloutput:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
381
CreateaprojectinAndroidStudioandnamedit“Intents”.Makeanactivity,whichwould
consistsJavafile;MainActivity.javaandanxmlfileforUserinterfacewhichwouldbe
activity_main.xml
Step1:Let’sdesigntheUIofactivity_main.xml:
● FirstdesignthetextviewdisplayingbasicdetailsoftheApp
● SeconddesignthetwobuttonofExplicitIntentExampleandImplicitIntentExample
Belowisthecompletecodeofactivity_main.xml
<RelativeLayout
x
mlns:android ="
http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools" a
ndroid:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingLeft
="
@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
android:paddingBottom
="@dimen/activity_vertical_margin"
t
ools:context="
.MainActivity"
>
<TextView
android:layout_width
="
wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
382
ndroid:layout_height
a ="wrap_content"
android:textAppearance
="?android:attr/textAppearanceMedium"
android:text
="
IfyouclickonExplicit example
we
will
navigate
to
second
activity
within
App
and
ifyouclickonImplicit example AbhiAndroid
Homepage
will
open
in
Browser"
android:id
="@+id/textView2"
android:clickable
="
false"
android:layout_alignParentTop
="
true"
android:layout_alignParentStart
="true"
android:layout_marginTop
="
42dp"
android:background
="#3e7d02"
android:textColor
="
#ffffff" />
<Button
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:text
="
Explicit IntentExample"
android:id
="@+id/explicit_Intent"
android:layout_alignParentTop
="
true"
android:layout_centerHorizontal
="true"
android:layout_marginTop
="
147dp" /
>
<Button
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:text
="
Implicit IntentExample"
android:id
="@+id/implicit_Intent"
android:layout_centerVertical
="
true"
android:layout_centerHorizontal
="true"/>
</RelativeLayout>
Step2:DesigntheUIofsecondactivityactivity_second.xml
NowletsdesignUIofanotheractivitywhereuserwillnavigateafterheclickonExplicit
Examplebutton.Gotolayoutfolder,createanewactivityandnameitactivity_second.xml.
InthisactivitywewillsimplyuseTextViewtotelluserheisnowonsecondactivity.
Belowisthecompletecodeofactivity_second.xml
<?
xml
version
="
1.0"
encoding ="
utf-8"?>
<RelativeLayoutx
mlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools" a
ndroid:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingLeft ="
@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:background
="
#CCEEAA"
tools:context
="
com.example.android.intents.SecondActivity" >
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
383
<TextView
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:textAppearance
="?android:attr/textAppearanceLarge"
android:text
="
This
isSecondActivity"
android:id
="
@+id/textView"
android:layout_centerVertical
="
true"
android:layout_centerHorizontal
="
true"
/
>
</RelativeLayout>
Step3:ImplementonClickeventforImplicitAndExplicitButtoninside
MainActivity.java
NowwewillusesetOnClickListener()methodtoimplementOnClickeventonboththebutton.
ImplicitbuttonwillopenAbhiAndroid.comhomepageinbrowserandExplicitbuttonwillmove
toSecondActivity.java.
BelowisthecompletecodeofMainActivity.java
package
com
.e
xample .android .intents ;
import
android .c
ontent .Intent ;
import
android .n
et.Uri;
import
android .s
upport .v7
.app.A
ppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .V
iew ;
import
android .w
idget .Button ;
public
c
lassMainActivity e
xtends A
ppCompatActivity {
Button
explicit_btn ,implicit_btn ;
@Override
protected
v
oidonCreate (B
undle savedInstanceState ){
super
.o
nCreate (savedInstanceState );
s
etContentView (R.
layout .activity_main );
e
xplicit_btn= (B
utton )f
indViewById (R.i
d.e
xplicit_Intent );
i
mplicit_btn= (B
utton )findViewById (R.
id
.implicit_Intent );
//implement
Onclick event for Explicit Intent
e
xplicit_btn .setOnClickListener (newV
iew .O
nClickListener ()
{
@Override
publicvoid
onClick (View
v){
Intent
intent= new I
ntent (getBaseContext (),
S
econdActivity
.c
lass
);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
384
s
tartActivity
(i
ntent
);
}
});
//implement
onClick
event
for
Implicit
Intent
i
mplicit_btn.s
etOnClickListener(n
ew V
iew
.O
nClickListener
()
{
@Override
public
v
oid
onClick
(V
iew
v){
ntent
I
intent=
new
Intent(I
ntent
.A
CTION_VIEW
);
i
ntent
.s
etData
(U
ri.p
arse("
http://www.abhiandroid.com"
));
s
tartActivity
(i
ntent );
}
});
}
}
Step4:CreateANewJAVAclassnameSecondActivity
NowweneedtocreateanotherSecondActivity.javawhichwillsimplyopenthelayoutof
activity_second.xml.AlsowewilluseToasttodisplaymessagethatheisonsecondactivity.
BelowisthecompletecodeofSecondActivity.java:
packagecom
.e
xample .android .i
ntents ;
import
android .s
upport .v
7.app
.AppCompatActivity ;
import
android .o
s.B
undle ;
import
android .w
idget .T
oast ;
publicc
lassS
econdActivity e
xtends A
ppCompatActivity{
@Override
protected
v
oidonCreate (B
undle
savedInstanceState){
super
.o
nCreate (savedInstanceState );
s
etContentView (R.
layout.a
ctivity_second );
Toast
.m
akeText (getApplicationContext (),
"
We
aremoved
to
second
Activity" ,T
oast.LENGTH_LONG ).show
();
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
385
Step5:Manifestfile:
MakesureManifestfilehasboththeMainActivityandSecondActivitylistedit.Alsohere
MainActivityisourmainactivitywhichwillbelaunchedfirst.Somakesureintent-filteris
correctlyaddedjustbelowMainActivity.
BelowisthecodeofManifestfile:
<?xmlversion="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.intents">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activityandroid:name=".MainActivity">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activityandroid:name=".SecondActivity">
</activity>
</application>
</manifest>
Output:
NowruntheaboveprograminyourEmulator.TheAppwilllooklikethis:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
386
FirstClickonExplicitIntentExample.TheSecondActivitywillbeopenwithintheApp:
NowgobackinEmulatorandclickonImplicitIntentExample.TheAbhiAndroid.com
homepagewillopeninBrowser(makesureyouhaveinternet):
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
387
IntentUsesInAndroid:
AndroidusesIntentsforfacilitatingcommunicationbetweenitscomponentslikeActivities,
ServicesandBroadcastReceivers.
IntentforanActivity:
EveryscreeninAndroidapplicationrepresentsanactivity.Tostartanewactivityyouneedto
passanIntentobjecttostartActivity()method.ThisIntentobjecthelpstostartanewactivity
andpassingdatatothesecondactivity.
IntentforServices:
ServicesworkinbackgroundofanAndroidapplicationanditdoesnotrequireanyuser
Interface.IntentscouldbeusedtostartaServicethatperformsone-timetask(forexample:
Downloadingsomefile)orforstartingaServiceyouneedtopassIntenttostartService()
method.
IntentforBroadcastReceivers:
Therearevariousmessagethatanappreceives,thesemessagesarecalledasBroadcast
Receivers.(Forexample,abroadcastmessagecouldbeinitiatedtointimatethatthefile
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
388
downloadingiscompletedandreadytouse).Androidsysteminitiatessomebroadcastmessage
onseveralevents,suchasSystemReboot,LowBatterywarningmessageetc.
ImportanceofusingIntentsinAndroidApplications:
Wheneveryouneedtonavigatetoanotheractivityofyourapporyouneedtosendsome
informationtonextactivitythenwecanalwaysprefertoIntentsfordoingso.
Intentsarereallyeasytohandleanditfacilitatescommunicationofcomponentsandactivities
ofyourapplication.Moreoveryoucancommunicatetoanotherapplicationandsendsomedata
toanotherapplicationusingIntents.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
389
InternalStorage
Inthistutorialwearegoingtolearnaboutinternalstorageofdata/filesinAndroidAppusing
exampleoryoucansaytheprimarymemoryofyourphone.Itisalsoimportanttonotethatthe
dataisstoredinafilespecifiedbytheuserbutusercannotaccessthatfile,alsothisfilecan
onlybeaccessedbytheapplicationitself.
ImportantPointsAboutInternalStorageInAndroid:
1. Thestoreddatainmemoryisallowedtoreadandwritefiles.
2. Whenfilesarestoredininternalstoragethesefilecanonlybeaccessedbythe
applicationitselfnotbyotherapplications.
3. Thesefilesinstorageexisttilltheapplicationstaysoverthedevice,asyouuninstall
associatedfilesgetremovedautomatically.
4. Thefilesarestoredindirectorydata/datawhichisfollowedbytheapplicationpackage
name.
5. Usercanexplicitlygrantthepermissiontootherappstoaccessfiles.
6. Tomakethedataprivatei.eyoucanuseMODE_PRIVATEasdiscussedbelowaboutthe
modes.
7. Techniqueisbestsuitedwhendatacanonlybeaccessbytheapplicationneitherbythe
usernorbyotherapps.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
390
8. Thedataisstoredinafilewhichcontainsdatainbitformatsoit’srequiredtoconvert
databeforeaddingittoafileorbeforeextractingfromafile.
ModesofInternalStorage
MODE_PRIVATE—I nprivatemodethedatastoredearlierisalwaysoverriddenbythecurrent
datai.eeverytimeyoutrytocommitanewwritetoafilewhichremovesoroverridethe
previouscontent.WehaveusedMODE_PRIVATEintheexampleattheendofthisarticle.
MODE_APPEND—I nthismodethedataisappendtotheexistingcontenti.ekeepaddingdata.
WritedatatofileinInternalStorage:
● Definethefilenameasstringandalsodefinedatayouwannawritetofileasstringorin
anyformatgeneratedfromapporanyothersource.
● UseFileOutputStreammethodbycreatingitsobjectasdefined.
● Convertdataintobytestreambeforewritingoverfilebecausefileacceptsonlybyte
formatfurtherclosethefileusingfileobject.
String
F
ile_Name="Demo.txt" ;/
/givesfile
name
String
D
ata="
Hello!!";/
/define data
FileOutputStreamfileobj=openFileOutput(F
ile_Name
,C
ontext
.M
ODE_PRIVATE
);
byte
[]
B
yteArray=D
ata
.getBytes();
/
/Convertsinto
bytes
stream
fileobj
.write
(B
yteArray);/
/writingtofile
fileobj
.close
();
/
/Fileclosed
InternalStorageExampleInAndroidStudio
Belowistheexampletoshowhowusercanusedinternalmemoryfordatastorage.Hereweare
creatingtwoactivities,thefirstactivitycontaintheformthatwillstoredatainfileandsecond
isusedtoloaddatathatissavedbefore.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
391
Step1:CreateanewprojectandnameitInternalStorageDemo.
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
Inthiscodesimplyaddtextview,edittextandbuttonwithonclickfunctionality.
<?
xml
version
="
1.0"
encoding ="
utf-8"?>
<RelativeLayoutxmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:id
="
@+id/activity_main"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
="
com.example.internalstoragedemo.MainActivity" >
<TextView
android:text
="@string/name"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
392
ndroid:layout_alignParentTop
a ="
true"
android:layout_alignParentLeft
="true"
android:layout_alignParentStart
="true"
android:layout_marginLeft
="
51dp"
android:layout_marginStart
="51dp"
android:layout_marginTop
="59dp"
android:id
="
@+id/txtname"
android:textStyle
="bold|italic"
android:textSize
="
18sp"/
>
<TextView
android:text
="
@string/password"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_below
="
@+id/txtname"
android:layout_alignLeft
="@+id/txtname"
android:layout_alignStart
="
@+id/txtname"
android:layout_marginTop
="56dp"
android:id
="
@+id/txtpass"
android:textStyle
="bold|italic"
android:textSize
="
18sp" /
>
<EditText
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:inputType
="
textPersonName"
android:ems
="8"
android:layout_alignParentTop
="true"
android:layout_toRightOf
="
@+id/txtpass"
android:layout_toEndOf
="@+id/txtpass"
android:layout_marginLeft
="21dp"
android:layout_marginStart
="21dp"
android:layout_marginTop
="
48dp"
android:id
="
@+id/editName" />
<EditText
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:inputType
="
textPassword"
android:ems
="10"
android:layout_below
="
@+id/editName"
android:layout_alignLeft
="
@+id/editName"
android:layout_alignStart
="@+id/editName"
android:layout_marginTop
="
35dp"
android:id
="
@+id/editPass" />
<Button
android:text
="
@string/save"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_below
="
@+id/editPass"
android:layout_alignLeft
="@+id/txtpass"
android:layout_alignStart
="
@+id/txtpass"
android:layout_marginTop
="86dp"
android:id
="
@+id/button"
android:onClick
="
save"
/> //
OnClick
"save"
<Button
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
393
ndroid:text
a ="
@string/next"
android:la
android:layout_height
="
wrap_content"
android:layout_alignTop
="
@+id/button"
android:layout_alignRight
="
@+id/editName"
android:layout_alignEnd
="
@+id/editName"
android:layout_marginRight
="25dp"
android:layout_marginEnd
="25dp"
android:id
="@+id/button2"
android:onClick
="
next"
/>
// OnClick
"next"
</RelativeLayout>
Step3:O
pensrc->package->MainActivity.java
InthisstepweopenMainActivityandaddthefunctionsdefinedoverbuttononclicki.esaveor
next.Thesavefunctiongetthedatafromedittextandsaveitinbyteformatinsidefile.Herewe
alsousedToasttodisplaythepathwherefileisstoredwithfilename.Thenextfunctionuses
intenttomovetothenextactivityassociatedwithit.
packagecom
.e
xample .i
nternalstoragedemo ;
import
android .c
ontent .C
ontext ;
import
android .c
ontent .I
ntent ;
import
android .s
upport .v
7.app.A
ppCompatActivity ;
import
android .o
s.Bundle ;
import
android .v
iew .View;
import
android .w
idget .E
ditText ;
import
android .w
idget .T
oast ;
import
java.i
o .F
ile ;
import
java.i
o .F
ileOutputStream ;
import
java.i
o .I
OException ;
publicc
lassMainActivity extends A
ppCompatActivity {
EditText
editname ,e
ditpass ;
@Override
protected
void
onCreate (Bundle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .a
ctivity_main );
e
ditname= (
EditText )findViewById (R.
id
.editName);
e
ditpass =(E
ditText )findViewById (R
.i
d.e
ditPass );
}
public
v
oid save (V
iew
view ) //SAVE
{
File
file=null ;
String
name=
editname .getText ().
toString ();
String
password= editpass .getText().toString ();
FileOutputStream
fileOutputStream= null
;
try{
n
ame= name+ "
";
f
ile= getFilesDir ();
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
394
f
ileOutputStream=
openFileOutput
("
Code.txt"
,C
ontext
.M
ODE_PRIVATE
);
/
/MODE
PRIVATE
f
ileOutputStream .w
rite (n
ame .g
etBytes());
f
ileOutputStream .w
rite (p
assword .getBytes
());
Toast
.makeText (this,"Saved \n"
+
"Path
--"
+file+
"
\tCode.txt"
,
Toast
.LENGTH_SHORT ).
show ();
e
ditname .setText ("
");
e
ditpass .setText ("
");
return
;
}catch (E
xception ex
){
e
x.p
rintStackTrace ();
}finally {
try
{
f
ileOutputStream .close ();
}c
atch (I
OException e){
e
.p
rintStackTrace ();
}
}
}
public
v
oid next (View view) / /NEXT
{
Toast
.makeText (this,"NEXT" ,T
oast .L
ENGTH_SHORT ).
show();
Intent
intent =new I
ntent (t
his ,Main2Activity .c
lass
);
s
tartActivity (intent );
}
}
Step4:O
penres->layout->activity_main2.xml(or)main2.xmlandaddfollowingcode:
Inthisactivitythelayoutisjustsimilarwiththemain.xml.
<?
xml
version
="
1.0"
encoding ="
utf-8" ?>
<RelativeLayoutxmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:id
="
@+id/activity_main2"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
="
com.example.internalstoragedemo.Main2Activity" >
<TextView
android:text
="@string/getname"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_alignParentTop
="
true"
android:layout_alignRight
="
@+id/button3"
android:layout_alignEnd
="
@+id/button3"
android:layout_marginRight
="11dp"
android:layout_marginEnd
="11dp"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
395
ndroid:layout_marginTop
a ="
76dp"
android:id
="
@+id/textView3"
android:textSize
="
18sp"
android:textStyle
="bold|italic"/>
<TextView
android:text
="
@string/getpassword"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_below
="
@+id/textView3"
android:layout_alignRight
="
@+id/textView3"
android:layout_alignEnd
="
@+id/textView3"
android:layout_marginTop
="33dp"
android:id
="
@+id/textView4"
android:textStyle
="bold|italic"
android:textSize
="
18sp" /
>
<TextView
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_above
="
@+id/textView4"
android:layout_alignLeft
="@+id/button4"
android:layout_alignStart
="
@+id/button4"
android:id
="
@+id/getname"
android:textStyle
="bold|italic"
android:textSize
="
18sp" /
>
<TextView
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_alignBottom
="@+id/textView4"
android:layout_alignLeft
="@+id/getname"
android:layout_alignStart
="
@+id/getname"
android:id
="
@+id/getpass"
android:textStyle
="bold|italic"
android:textSize
="
18sp" /
>
<Button
android:text
="
@string/load"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:id
="
@+id/button3"
android:layout_marginLeft
="35dp"
android:layout_marginStart
="
35dp"
android:onClick
="
load"
android:layout_below
="
@+id/textView4"
android:layout_alignParentLeft
="
true"
android:layout_alignParentStart
="true"
android:layout_marginTop
="
80dp"/>
<Button
android:text
="
@string/back"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_marginRight
="
54dp"
android:layout_marginEnd
="
54dp"
android:id
="
@+id/button4"
android:onClick
="
back"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
396
ndroid:layout_alignBaseline
a ="
@+id/button3"
android:layout_alignBottom
="
@+id/button3"
android:layout_alignParentRight
="
true"
android:layout_alignParentEnd
="true"
/
>
</RelativeLayout>
Step5:O
pensrc->package->MainActivity2.java
InthisstepweopenMainActivity2andaddthefunctionsdefinedoverbutton’sonclicki.eload
orback.Theloadfunctionretrievethedatafromthefile,addittotheStringBufferandfurther
setthetextoverthetextview‘s.The backfunctioncontainintenttomovebacktomainactivity.
packagecom
.example .i
nternalstoragedemo ;
import
android .c
ontent .I
ntent ;
import
android .s
upport .v
7.app.AppCompatActivity ;
import
android .o
s.B
undle ;
import
android .u
til .Log
;
import
android .v
iew .View;
import
android .w
idget .T
extView ;
import
android .w
idget .T
oast ;
import
java.io.F
ileInputStream ;
publicc
lass Main2Activity extends AppCompatActivity {
TextView
getname ,
getpass ;
@Override
protected
v
oid
onCreate (B
undle savedInstanceState ){
super
.o
nCreate (savedInstanceState );
s
etContentView (R.
layout .activity_main2 );
g
etname= (T
extView )f
indViewById (R
.i
d.g
etname );
g
etpass= (T
extView )f
indViewById (R
.i
d.g
etpass );
}
public
void load (V
iew view)
{
try
{
FileInputStream fileInputStream= openFileInput ("
Code.txt");
int
read= -
1;
StringBuffer buffer= newS
tringBuffer ();
while ((
read= f
ileInputStream .r
ead ())!= -
1)
{
b
uffer .a
ppend ((char )read
);
}
Log.d(
"
Code" ,buffer .toString ());
String
name= buffer .substring (0,
buffer.indexOf ("")
);
String p
ass =
buffer .substring (buffer .i
ndexOf ("
")
+1);
g
etname .setText (n
ame );
g
etpass .setText (p
ass );
}c
atch (E
xception e)
{
e
.p
rintStackTrace ();
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
397
}
Toast
.m
akeText
(t
his
,"
Loaded"
,T
oast
.L
ENGTH_SHORT
).
show
();
}
ublic
p v
oid b
ack
(View
view
)
{
Toast
.m
akeText (t
his,"
Back",T
oast.L
ENGTH_SHORT).
show
();
Intent
intent
=new
I
ntent(t
his,M
ainActivity.c
lass);
s
tartActivity(intent);
}
}
Output:
Nowruntheappandyouwillseeloginformonthescreen.Adddatainthefieldsandsaveit.
Furtherclicknexttomovetonextactivityandloaddatathatissavedbefore.
BonusTip
Youcanviewthefilewhichcontaindatathatyoustored,ifyounoticedthatwhilesavingatoast
appearswiththepathwherefileisstoredlet’slocatethatfile.
ImportantNote:T
hefilewillonlybeviewableifyouruntheAppusingAndroidStudio
emulatorandnotingenymotionoranyotherexternalalternativeemulator.
MovetoTools->Android->AndroidDeviceMonitorandopenAndroidDeviceMonitor.
Selecttheprocessi.einternalstoragedemo,selectFileExplorerfind
data/data/[package_name]/files/[file.txt]
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
398
Ingivenexampleitisdata/data/com.example.internalstoragedemo/files/Code.txt.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
399
ExternalStorage
Inthistutorialwegonnastudyaboutstorageofdata/filesinandroidexternalstorageoryoucan
saythesecondarymemory/SDcardofyourphone.Thedataisstoredinafilespecifiedbythe
useritselfandusercanaccessthesefile.Thesefilesareonlyaccessibletilltheapplicationexits
oryouhaveSDcardmountedonyourdevice.
ImportantNote:I tisnecessarytoaddexternalstoragethepermissiontoreadandwrite.For
thatyouneedtoaddpermissioninandroidManifestfile.
OpenAndroidManifest.xmlfileandaddpermissionstoitjustafterthepackagename.
<uses-permission
a
ndroid:name="
android.permission.WRITE_EXTERNAL_STORAGE"
/
>
<uses-permission
android:name
="
android.permission.READ_EXTERNAL_STORAGE"
/>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
400
ExternalStorageAvailabilityInAndroidStudio
ToavoidcrashingappitisrequiredtocheckbeforewhetherstorageSDcardisavailableforread
&writeoperations.getExternalStorageState()methodisusedtodeterminethestateofthe
storagemediai.eSDcardismounted,isitreadable,itiswritableetc..allthiskindof
information.
boolean
isAvailable =false;
boolean
isWritable =f
alse ;
boolean
isReadable =f
alse ;
String state= E
nvironment .getExternalStorageState
();
if
(Environment .M
EDIA_MOUNTED .e
quals
(s
tate
)){
//Read and writeoperation possible
isAvailable =t
rue;
isWritable =t
rue;
isReadable =t
rue;
}
e
lse if
(E
nvironment .M
EDIA_MOUNTED_READ_ONLY .e
quals
(state
)){
/
/Read operation possible
isAvailable =t
rue;
isWritable =f
alse;
isReadable =t
rue;
}
e lse{
/
/ SDcardnotmounted
isAvailable= false;
isWritable =f
alse;
isReadable =f
alse;}
MethodstoStoreDataInAndroid:
getExternalStorageDirectory()–OlderwaytoaccessexternalstorageinAPI Levellessthan7.
Itisabsolutenowandnotrecommended.Itdirectlygetthereferencetotherootdirectoryof
yourexternalstorageorSDCard.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
401
getExternalFilesDir(Stringtype)–I tisrecommendedwaytoenableustocreateprivatefiles
specifictoappandfilesareremovedasappisuninstalled.Exampleisappprivatedata.
getExternalStoragePublicDirectory():Thisiscurrentrecommendedwaythatenableusto
keepfilespublicandarenotdeletedwiththeappuninstallation.Exampleimagesclickedbythe
cameraexistsevenweuninstallthecameraapp.
ExternalStorageExampleInAndroidStudio
Belowistheexampletoshowhowusercanuseexternalmemoryfordatastorage.Hereweare
creatingtwoactivities,thefirstactivitycontaintheformthatwillstoredatainfileandsecond
isusedtoloaddatawhichissaved.
Step1:C
reateanewprojectandnameitExternalStorageExample.
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
402
Inthiscodesimplyaddtextview,edittextandbuttonforonclickfunctionality.
<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.externalstorageexample.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="46dp"
android:gravity="center"
android:text="@string/add_text"
android:textSize="18sp"
android:textStyle="bold|italic"/>
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignStart="@+id/button"
android:layout_marginBottom="52dp"
android:layout_marginLeft="96dp"
android:layout_marginStart="96dp"
android:onClick="next"
android:text="@string/click_to_view"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
403
ndroid:layout_height="wrap_content"
a
android:layout_above="@+id/button4"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="22dp"
android:layout_marginEnd="32dp"
android:layout_marginRight="32dp"
android:onClick="savePublic"
android:text="@string/save_as_public"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button2"
android:layout_alignBottom="@+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:onClick="savePrivate"
android:text="@string/save_as_private"/>
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/textView"
android:layout_marginTop="16dp"
android:ems="10"
android:gravity="center_vertical|center"
android:inputType="textMultiLine"/>
</RelativeLayout>
Step3:O
pensrc->package->MainActivity.java
InthisstepweopenMainActivityandaddthefunctionsdefinedoverbuttonsonclick.The
savePrivateandsavePublicfunctiongetthedatafromedittextandsaveitinbyteformatinfile.
Alsotoastisusedtodisplaythepathwherefileisstoredwithfilename.Thenextfunctionuses
intenttomovetothenextactivityassociatedwithit.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
404
ImportantNote:T
hereisadifferencewhileretrievingdatawithdifferentAPIlevel.The
permissionconcepthaschangedsinceAPI23.BeforeAPIlevel23theuserwasaskedduring
installation,afterAPIlevel23theuserisaskedduringruntime.Soanadditionalruntime
permissionisaddedintheapplicationoperatingovertheAPIlevelabove23.
packagecom
.e
xample .e
xternalstorageexample ;
import
android .Manifest ;
import
android .content .I
ntent ;
import
android .os.E
nvironment ;
import
android .support .v
4.app.ActivityCompat ;
import
android .support .v
7.app.AppCompatActivity ;
import
android .os.B
undle ;
import
android .view .V
iew ;
import
android .widget .E
ditText ;
import
android .widget .T
oast ;
import
java.i
o.File ;
import
java.i
o.FileOutputStream ;
import
java.i
o.IOException ;
publicc
lassMainActivity extends A
ppCompatActivity {
EditText
editText ;
private
i
nt
STORAGE_PERMISSION_CODE= 23;
@Override
protected
v
oid onCreate (B
undle savedInstanceState ){
super
.o
nCreate (savedInstanceState );
s
etContentView (R.
layout .activity_main );
e
ditText= (E
ditText )findViewById (R.
id
.editText2 );
}
public
v
oid n
ext (Viewview ){
Intent
intent= new I
ntent (MainActivity .this,M ain2Activity.c
lass
);
s
tartActivity (i
ntent );
}
public
v
oid
savePublic (Viewview ){
//Permission
toaccess external storage
ActivityCompat
.requestPermissions (t
his ,new
String[]{Manifest .p
ermission .READ_EXTERNAL_STORAGE },
STORAGE_PERMISSION_CODE );
String
info= editText .getText ().toString ();
File
folder=
Environment .g
etExternalStoragePublicDirectory (E
nvironment .D
IRECTORY_ALARMS);//Folder
Name
File
myFile= new F
ile (folder ,"myData1.txt" );//Filename
w
riteData (myFile ,info );
e
ditText .s
etText (""
);
}
public
v
oid
savePrivate (V
iew view){
String
info= editText .getText ().toString ();
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
405
ile
F folder=
getExternalFilesDir ("
AbhiAndroid");
//
FolderName
File
myFile=n
ewF
ile(f
older
,"
myData2.txt"
);
//Filename
w
riteData(myFile
,info);
e
ditText.s
etText("
");
}
private
v
oidwriteData (F
ile
myFile ,String
data){
FileOutputStream
fileOutputStream= null ;
try
{
f
ileOutputStream= newF
ileOutputStream (m
yFile
);
f
ileOutputStream .w
rite (d
ata .g
etBytes ());
Toast .makeText (t
his ,"Done" +
myFile .g
etAbsolutePath
(),
Toast
.LENGTH_SHORT ).show();
}c
atch(E
xception
e){
e
.p
rintStackTrace ();
}f
inally {
if(
fileOutputStream! =
null){
try
{
f
ileOutputStream .c
lose ();
}c
atch (
IOException
e){
e
.p
rintStackTrace ();
}
}
}
}
}
Step4:O
penres->layout->activity_main2.xml(or)main2.xmlandaddfollowingcode:
Inthisactivitythelayoutisjustsimilarwiththemain.xml.
<?
xml
version
="
1.0"
encoding ="
utf-8" ?>
<RelativeLayoutxmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:id
="
@+id/activity_main2"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
="
com.example.externalstorageexample.Main2Activity" >
<TextView
android:id
="
@+id/getText"
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
android:layout_alignParentLeft
="true"
android:layout_alignParentStart
="true"
android:layout_alignParentTop
="
true"
android:layout_marginTop
="
33dp"
android:gravity
="center"
android:text
="
"
android:textSize
="
18sp"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
406
android:textStyle
="
bold|italic"
/
>
<Button
android:id
="
@+id/button3"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_above
="
@+id/button5"
android:layout_alignParentEnd
="
true"
android:layout_alignParentRight
="
true"
android:onClick
="
getPublic"
android:text
="
@string/show_public_data" /
>
<Button
android:id
="
@+id/button2"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_alignParentLeft
="
true"
android:layout_alignParentStart
="true"
android:layout_below
="
@+id/getText"
android:layout_marginTop
="
178dp"
android:onClick
="
getPrivate"
android:text
="
@string/show_private_data"
tools:ignore
="
UnknownId"/
>
<Button
android:id
="
@+id/button5"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_below
="
@+id/button2"
android:layout_centerHorizontal
="true"
android:layout_marginTop
="
59dp"
android:onClick
="
back"
android:text
="
@string/back"/
>
</RelativeLayout>
Step5:O
pensrc->package->MainActivity2.java
InthisstepweopenMainActivity2andaddthefunctionsdefinedoverbutton‘sonclick.The
getPrivateandgetPublicfunctionretrievethedatafromthefile,addittothebufferandfurther
setthetextoverthetextview‘s.The backfunctioncontainintenttomovebacktomainactivity.
package
com
.e
xample
.externalstorageexample;
import
android.c
ontent.I
ntent;
import
android.o
s
.E
nvironment ;
import
android.s
upport.v
7.a
pp
.A
ppCompatActivity
;
import
android.o
s
.B
undle;
import
android.v
iew.V
iew;
import
android.w
idget.T
extView ;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
407
import
java .i
o .*;
publicc
lass Main2Activity extends A
ppCompatActivity {
TextView
showText ;
@Override
protected
void onCreate (B
undle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .activity_main2 );
s
howText= (T
extView )findViewById (R.i
d.g
etText );
}
public
v
oid back (View
view ){
Intent
intent= new I
ntent (M
ain2Activity .this,MainActivity .c
lass
);
s
tartActivity (i
ntent );
}
public
v
oid getPublic (V
iew view){
File
folder=
Environment .g
etExternalStoragePublicDirectory (Environment .DIRECTORY_ALARMS );/
/
Folder
Name
File
myFile= new F
ile (folder ," myData1.txt" );/
/ Filename
String
text= getdata (m
yFile );
if
(
t
ext! = n
ull ){
s
howText .setText (text );
}e
lse {
s
howText .setText ("No Data" );
}
}
public
v
oid getPrivate (Viewview ){
File
folder= getExternalFilesDir ("
AbhiAndroid" );//
FolderName
File
myFile= new F
ile (folder ," myData2.txt" );/
/ Filename
String
text= getdata (m
yFile );
if
(
t
ext! = n
ull ){
s
howText .setText (text );
}e
lse {
s
howText .setText ("No Data" );
}
}
private
S
tring getdata (Filemyfile ){
FileInputStream
fileInputStream= null ;
try
{
f
ileInputStream =new F
ileInputStream (m
yfile );
int
i=-1;
StringBuffer buffer= new S
tringBuffer ();
while (
(i=fileInputStream .r
ead ()) !
=-
1)
{
b
uffer .append ((
char )i);
}
return buffer .t
oString ();
}c
atch (E
xception e)
{
e
.p
rintStackTrace ();
}f
inally {
if(
fileInputStream! =null ){
try
{
f
ileInputStream .c
lose ();
}c
atch (
IOException
e){
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
408
e
.p
rintStackTrace
();
}
}
}
return
n
ull
;
}
}
Output:
Nowruntheappandyouwillseeformonthescreen.Adddatainthefieldandsaveit.Further
clicknexttomovetonextactivityandgetdatathatissavedbeforeaspublicorprivate.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
409
SharedPreference
SharedPreferenceinAndroidareusedtosavedatabasedonkey-valuepair.Ifwegodeepinto
understandingofword:sharedmeanstodistributedatawithinandpreferencemeans
somethingimportantorpreferable,soSharedPreferencesdataissharedandpreferreddata.
SharedPreferencecanbeusedtosaveprimitivedatatype:string,long,int,floatandBoolean.
WhatIsPreferenceFile?
Beforewebeginexplainingsharedpreference,itisimportanttounderstandpreferencefile.
Apreferencefileisactuallyaxmlfilesavedininternalmemoryofdevice.Everyapplication
havesomedatastoredinmemoryinadirectorydata/data/applicationpackagenamei.e
data/data/com.abhiandroid.abhiappsowhenevergetSharedPreferences(Stringname,intmode)
functiongetcalleditvalidatesthefilethatifitexistsoritdoesn’tthenanewxmliscreated
withpassedname.
TwoWaysToSaveDataThroughSharedPreference:
TherearetwodifferentwaystosavedatainAndroidthroughSharedPreferences–Oneisusing
Activitybasedpreferencesandotheriscreatingcustompreferences.
ActivityPreferences:
● ForactivitypreferencesdeveloperhavetocallfunctiongetPreferences(intmode)
availableinActivityclass
● UseonlywhenonepreferencefileisneededinActivity
● Itdoesn’trequirenameasitwillbetheonlypreferencefileforthisactivity
● Developerdoesn’tusuallypreferusingthiseveniftheyneedonlyonepreferencefilein
Activity.TheypreferusingcustomgetSharedPreferences(Stringname,intmode).
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
410
TouseactivitypreferencesdeveloperhavetocallfunctiongetPreferences(intmode)available
inActivityclass.ThefunctiongetPreferences(intmode)calltheotherfunctionusedtocreate
custompreferencesi.egetSharedPreferences(Stringname,intmode).JustbecauseActivity
containsonlyonepreferencefilesogetPreferences(intmode)functionsimplypassthenameof
Activityclasstocreateapreferencefile.
ImportantNote:ModearediscussedinCustompreferences.
CustomPreferences:
DeveloperneedstousegetSharedPreferences(Stringname,intmode)forcustompreferences
UsedincaseswhenmorethanonepreferencefilerequiredinActivity
Nameofthepreferencefileispassedinfirstparameter
CustomPreferencescanbecreatedbycallingfunctiongetSharedPreferences(Stringname,int
mode),itcanbecalledfromanywhereintheapplicationwithreferenceofContext.Herename
isanypreferrednameforexample:User,Booketc.andmodeisusedtosetkindofprivacyfor
file.
ModeAndItsTypeInSharedPreference:
Tocreateactivitybasedpreferencesorcustompreferencesdeveloperhavetopassmodetolet
thesystemknowaboutprivacyofpreferencefile.
BeforewebeginabriefdiscussiononContext
ContextisanabstractclassusedtogetglobalinformationinAndroidApplicationresourceslike
strings,values,drawables,assetsetc.Heremodesaredeclaredandstaticfinalconstantin
Contextclass.
TherearethreetypesofModeinSharedPreference:
Context.MODE_PRIVATE–defaultvalue(Notaccessibleoutsideofyourapplication)
Context.MODE_WORLD_READABLE–readabletootherapps
Context.MODE_WORLD_WRITEABLE–read/writetootherapps
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
411
MODE_PRIVATE–Itisadefaultmode.MODE_PRIVATEmeansthatwhenanypreferencefile
iscreatedwithprivatemodethenitwillnotbeaccessibleoutsideofyourapplication.Thisis
themostcommonmodewhichisused.
MODE_WORLD_READABLE–Ifdevelopercreatesasharedpreferencefileusingmodeworld
readablethenitcanbereadbyanyonewhoknowsit’sname,soanyotheroutsideapplication
caneasilyreaddataofyourapp.ThismodeisveryrarelyusedinApp.
MODE_WORLD_WRITEABLE–I t’ssimilartomodeworldreadablebutwithbothkindof
accessesi.ereadandwrite.ThismodeisneverusedinAppbyDeveloper.
ImportantGoogleRecommendNamingConventionForPreferenceFile:
PleasemakesuretofollowrecommendationbyGooglewhilegivingpreferencefilename.
Googlerecommendstogivenameasapplicationpackagename+preferredname.
CreatingSharedPreference:
Asdiscussedabove,tocreatesharedpreferencedeveloperneedstocallgetPreferences(int
mode)orgetSharedPreferences(Stringname,intmode)method.Bothofthefunctionreturn
SharedPreferencesobjecttodealwithsaveandgetvaluesfrompreferencefile.
SharedPreferencesisasingletonclassmeansthisclasswillonlyhaveasingleobjectthroughout
theapplicationlifecycle.Howevertherecanmultiplepreferencefilessoallthepreferencefiles
canbereadandwriteusingSharedPreferencesclass.
SaveDataInSharedPreferences:
Step1:
TosavedatainSharedPreferencesdeveloperneedtocallededit()functionofSharedPreferences
classwhichreturnsEditorclassobject.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
412
Step2:
Editorclassprovidedifferentfunctiontosaveprimitivetimedata.Forexample,Editorhaveall
primitivedatafunctionincludingStringtypedataasputInt(StringkeyName,intvalue).
Commonprimitivefunctionformatis:put+PrimitiveTypename(Stringkeyname,Primitive
Typevalue)
Step3:
Nowmakesurethatkeynameshouldbeuniqueforanyvaluesyousaveotherwiseitwillbe
overrided.Toexactlysavethevaluesyouputindifferentprimitivefunctionsyoumustcall
commit()functionofEditor.
ReadorgetdatafromSharedPreferences
Step1:T
oreaddatafirstdeveloperhavetogetreferenceofSharedPreferencesobjectbycalling
getPreferences(intmode)orgetSharedPreferences(Stringname,intmode).
Step2:T
hendevelopercangetvaluesusingSharedPreferencesobjectbycallingdifferent
primitivetypefunctionstartingwithget+PrimitiveTypename.Hereeveryfunctionhasan
additionalparameterforeveryPrimitiveTypeasdefaultvalueincasethereisnovaluefound
correspondingtopassedkey.
Forexample,togetsavedintvaluejustcallg
etInt(“GameScore”,-1)functionwhere
“GameScore”iskeyand-1isadefaultvalueincasenovaluewassavedforGameScore.
RemoveDataOrClearAllData
Similartosavedatathereisafunctionremove(Stringkey)inSharedPreferences.Editorto
removeaparticularkeybaseddatafrompreferencefile
Toclearalldatajustcallfunctionclear()availableinSharedPreferences.Editor.Makesureto
callcommit()methodtosavechanges.Socleardatawillneverdeletethepreferencefilebut
makeitempty.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
413
CodeOfSaving&RetrievingDatainSharedPreference:
public s
tatic finalS
tring
PREFS_GAME ="
com.abhiandroid.abhiapp.GamePlay" ;
public s
tatic finalS
tring
GAME_SCORE ="
GameScore" ;
//======== Codetosave data===================
SharedPreferences sp=
getSharedPreferences (P
REFS_GAME,C
ontext
.M
ODE_PRIVATE
);
sp
.e
dit ().putInt (G
AME_SCORE ,1
00).commit
();
//========= Codetoget saved/retrieve data ==============
SharedPreferences sp=
getSharedPreferences (P
REFS_GAME,C
ontext
.M
ODE_PRIVATE
);
int
sc =
sp.g
etInt (G
AME_SCORE ,0
);
Log
.d(
"AbhiAndroid" ,"
achieved score is"+
sc
);
SharedPreferenceExample:
Let’suseSharedPreferenceforaverybasicpurposeofsavinglogindetailsofapersoni.e.email
andpasswordonhisdevice.Sohedon’thavetore-enterhislogindetailseverytimeheopens
theApp.
BelowisthefinaloutputwewillcreateanduseSharedPreferencetosaveSigninDetails:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
414
Step1:C
reateanewprojectandcreateanloginActivityactivity_login.xml.Inthiscreatea
loginUIaskinguseremailandpasswordwithanoptionofremembermecheckbox.Alsoa
buttondisplayingSigninorRegister.
BelowisthecompletecodeloginUIactivity_login.xml
<LinearLayoutx
mlns:android ="http://schemas.android.com/apk/res/android"
x
mlns:tools ="
http://schemas.android.com/tools"
a
ndroid:layout_width ="match_parent"
a
ndroid:layout_height ="match_parent"
a
ndroid:gravity ="
center_horizontal"
a
ndroid:orientation ="vertical"
a
ndroid:paddingBottom ="@dimen/activity_vertical_margin"
a
ndroid:paddingLeft ="@dimen/activity_horizontal_margin"
a
ndroid:paddingRight ="@dimen/activity_horizontal_margin"
a
ndroid:paddingTop ="@dimen/activity_vertical_margin"
t
ools:context ="com.samplesharedpreferences.LoginActivity" >
<!--
Loginprogress -->
<ProgressBar
android:id
="
@+id/login_progress"
style
="
?
android:a
ttr /progressBarStyleLarge "
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_marginBottom
="8dp"
android:visibility
="gone" />
<ScrollView
android:id
="
@+id/login_form"
android:layout_width
="
match_parent"
android:layout_height
="match_parent" >
<LinearLayout
android:id ="
@+id/email_login_form"
android:layout_width ="match_parent"
android:layout_height ="
wrap_content"
android:orientation ="
vertical" >
<android.support.design.widget.TextInputLayout
android:layout_width
="match_parent"
android:layout_height
="
wrap_content" >
<EditText
android:id ="@+id/email"
android:layout_width ="match_parent"
android:layout_height ="
wrap_content"
android:hint ="@string/prompt_email"
android:inputType ="
textEmailAddress"
android:maxLines ="1"
android:singleLine ="true" />
</android.support.design.widget.TextInputLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
415
<android.support.design.widget.TextInputLayout
android:layout_width
="match_parent"
android:layout_height
="wrap_content"
>
<EditText
android:id
="
@+id/password"
android:layout_width ="match_parent"
android:layout_height ="
wrap_content"
android:hint="
@string/prompt_password"
android:imeActionId ="
@+id/login"
android:imeActionLabel ="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="
1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<CheckBox
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
android:text
="
RememberMe"
android:id
="
@+id/checkBoxRememberMe" />
<Button
android:id
="
@+id/email_sign_in_button"
style
="
?a
ndroid:t
extAppearanceSmall "
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
android:layout_marginTop
="
16dp"
android:text
="
@string/action_sign_in"
android:textStyle
="
bold"/>
</LinearLayout>
/ScrollView>
<
</LinearLayout>
Step2:N
owletscodetheLoginActivity.javawherewewillcreateaLoginform.Belowisthe
completecodeofLoginActivity.javawithexplanationincludedincomment.
package
com
.s
amplesharedpreferences ;
import
android.a
nimation.A
nimator ;
import
android.a
nimation.A
nimatorListenerAdapter ;
import
android.a
nnotation.TargetApi ;
import
android.c
ontent
.C
ontext ;
import
android.c
ontent
.I
ntent ;
import
android.c
ontent
.S
haredPreferences ;
import
android.c
ontent
.p
m.P
ackageManager ;
import
android.s
upport
.a
nnotation .NonNull ;
import
android.s
upport
.d
esign .w
idget .S
nackbar ;
import
android.s
upport
.v
7.a
pp.A
ppCompatActivity ;
import
android.a
pp
.L
oaderManager .LoaderCallbacks ;
import
android.c
ontent
.C
ontentResolver ;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
416
import
android .c
ontent .CursorLoader ;
import
android .c
ontent .Loader ;
import
android .d
atabase .Cursor ;
import
android .n
et .U
ri;
import
android .o
s.AsyncTask ;
import
android .o
s.Build .V
ERSION ;
import
android .o
s.Build ;
import
android .o
s.Bundle ;
import
android .p
rovider .ContactsContract ;
import
android .t
ext .TextUtils ;
import
android .v
iew .KeyEvent ;
import
android .v
iew .View;
import
android .v
iew .View.OnClickListener ;
import
android .v
iew .inputmethod .E
ditorInfo ;
import
android .w
idget .A
rrayAdapter ;
import
android .w
idget .A
utoCompleteTextView ;
import
android .w
idget .B
utton ;
import
android .w
idget .C
heckBox ;
import
android .w
idget .E
ditText ;
import
android .w
idget .T
extView ;
import
java.u
til .ArrayList ;
import
java.u
til .List ;
import s
tatic android .M
anifest .permission .R
EAD_CONTACTS ;
/**
*
A loginscreen that offers login viaemail/password.
*/
public c
lassLoginActivity extends A
ppCompatActivity {
//
UIreferences.
private
E
ditText
mEmailView ;
private
E
ditText
mPasswordView ;
private
C
heckBox
checkBoxRememberMe ;
@Override
protected
void
onCreate (Bundle
savedInstanceState ){
super
.onCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .a
ctivity_login );
//
Set up the login form.
m
EmailView= (E
ditText )findViewById (R.
id
.email );
m
PasswordView= (E
ditText )
findViewById (R
.i
d.p
assword );
m
PasswordView .setOnEditorActionListener (n
ew T
extView .O
nEditorActionListener ()
{
@Override
public b
oolean
onEditorAction (T
extView textView ,int
id
,KeyEvent
keyEvent
){
if
(
id==
R.i
d.login| |
id= =
EditorInfo .IME_NULL ){
a
ttemptLogin ();
return t
rue ;
}
return
f
alse ;
}
});
Button
mEmailSignInButton= (B
utton )findViewById (R.
id
.e
mail_sign_in_button );
m
EmailSignInButton .s
etOnClickListener (n
ew O
nClickListener ()
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
417
@Override
publicv
oid
onClick
(View
view
){
a
ttemptLogin();
}
});
c
heckBoxRememberMe= (
CheckBox
)
findViewById
(R.
id
.c
heckBoxRememberMe
);
//Here
wewill
validatesaved
preferences
if
(
!new
P
refManager(t
his).
isUserLogedOut
())
{
//user'semail
andpassword
both
are
saved inpreferences
s
tartHomeActivity();
}
}
**
/
*
Attemptstosign
inor
register the
account
specified
by
the
login
form.
*
If
thereareformerrors(invalidemail,
missing
fields,
etc.),
the
*
errorsarepresentedandnoactual
login
attempt
is
made.
*/
private
v
oid
attemptLogin()
{
/
/ Reset
errors.
m
EmailView
.s
etError
(n
ull
);
m
PasswordView
.s
etError
(n
ull);
/
/ Store
valuesatthe
time
of
the
login
attempt.
String
email=
mEmailView .g
etText
().
toString
();
String
password=
mPasswordView.g
etText
().
toString();
oolean
b
cancel=
f
alse
;
View
focusView=
n
ull
;
/
/ Checkfor
avalidpassword,if
the user
entered
one.
if
(
!TextUtils
.isEmpty(p
assword
)&&
!
isPasswordValid(p
assword
))
{
m
PasswordView .s
etError
(g
etString (R
.s
tring
.e
rror_invalid_password));
f
ocusView=
mPasswordView;
c
ancel=
t
rue;
}
/
/ Checkforavalidemail address.
if
(
T
extUtils .isEmpty(e
mail ))
{
m
EmailView .s
etError (g
etString (R
.s
tring
.e
rror_field_required));
f
ocusView= mEmailView ;
c
ancel=t
rue ;
}e
lsei
f
(
!isEmailValid (e
mail ))
{
m
EmailView .s
etError (g
etString (R
.s
tring
.e
rror_invalid_email
));
f
ocusView= mEmailView ;
c
ancel=t
rue ;
}
if
(c
ancel){
//
There was
an
error;don'tattempt
login
and
focus
the
first
//
formfieldwith
an
error.
f
ocusView .r
equestFocus
();
}e
lse{
//
savedatain
local
shared preferences
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
418
if
(
checkBoxRememberMe.i
sChecked
())
s
aveLoginDetails
(email
,
password);
s
tartHomeActivity();
}
}
private
v
oid
startHomeActivity
(){
Intent
intent=n
ew
I
ntent
(t
his ,H
omeActivity
.c
lass
);
s
tartActivity(i
ntent
);
f
inish
();
}
private
v
oid
saveLoginDetails
(S
tring
email
,String
password
){
new
P
refManager(t
his
).
saveLoginDetails
(e
mail,
password
);
}
private
b
oolean
isEmailValid(S
tring
email
){
//TODO:
Replacethis
withyour
own
logic
return
email.contains
("
@"
);
}
private
b
oolean
isPasswordValid(S
tring
password
){
//TODO:
Replace
this
withyour own
logic
return
password.l
ength
()
>
4;
}
}
Step3:C
reateanewjavaclassforSharedPreferencePrefManager.Belowisthecodeof
PrefManager.java
package com
.s
amplesharedpreferences ;
import
android .c
ontent .C
ontext ;
import
android .c
ontent .S
haredPreferences ;
/**
*
Class forSharedPreference
*/
public c
lassPrefManager {
Context
context;
PrefManager
(Context
context){
this
.c
ontext= context;
}
public
v
oidsaveLoginDetails (S
tring
email,S
tring
password){
SharedPreferences
sharedPreferences=
context
.getSharedPreferences
("LoginDetails"
,
Context .MODE_PRIVATE );
SharedPreferences
.E
ditor
editor= sharedPreferences.e
dit
();
e
ditor.p
utString ("Email",
email );
e
ditor.p
utString ("Password" ,password);
e
ditor.c
ommit();
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
419
}
public
S
tring
getEmail()
{
SharedPreferences
sharedPreferences=
context.g
etSharedPreferences("LoginDetails",
Context.M
ODE_PRIVATE );
return
sharedPreferences .g
etString("
Email","
");
}
public
b
oolean
isUserLogedOut (){
SharedPreferences
sharedPreferences=
context.g
etSharedPreferences("LoginDetails",
Context.M
ODE_PRIVATE );
boolean
isEmailEmpty=
sharedPreferences .g
etString ("
Email"
,"
"
).
isEmpty();
boolean
isPasswordEmpty= sharedPreferences.g
etString ("
Password"
,"
").
isEmpty
();
return
isEmailEmpty| |
isPasswordEmpty ;
}
}
Step4:DesignthesimpleHomeUIwherewewilldisplayWelcomemessagealongwithhis
savedemailaddressinSharedpreference.Belowisthecodeofcontent_home.xml
<?
xml
version
="
1.0"
encoding ="
utf-8"?>
<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:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
app:layout_behavior
="@string/appbar_scrolling_view_behavior"
tools:context
="com.samplesharedpreferences.HomeActivity"
tools:showIn
="
@layout/activity_home" >
<TextView
android:id
="@+id/textViewUser"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_centerInParent
="
true"
android:gravity
="center"
android:text
="Welcome" />
</RelativeLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
420
Step5:Manifestfile
MakesureinyourAndroidManifest.xmlIntentFilterforMainandLauncherissetinside
.LoginActivitybecausethenonlythatActivitywillopenfirst.
<?
xml
version ="
1.0"
encoding ="utf-8"
?>
<manifest
package="
com.samplesharedpreferences"
x
mlns:android ="
http://schemas.android.com/apk/res/android" >
<!--
Toauto-complete theemailtext fieldin
the
login
form
with the
user's
emails
-->
<uses-permission
a
ndroid:name ="
android.permission.GET_ACCOUNTS" />
<uses-permission
a
ndroid:name ="
android.permission.READ_PROFILE" />
<uses-permission
a
ndroid:name ="
android.permission.READ_CONTACTS" />
<application
android:allowBackup
="true"
android:icon
="
@mipmap/ic_launcher"
android:label
="@string/app_name"
android:supportsRtl
="true"
android:theme
="@style/AppTheme" >
<activity
android:name =".LoginActivity"
android:label ="
@string/app_name" >
<intent-filter>
<action
a
ndroid:name ="android.intent.action.MAIN" />
<category
a
ndroid:name ="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name =".HomeActivity"
android:label ="
@string/title_activity_home"
android:theme ="
@style/AppTheme.NoActionBar" >
</activity>
</application>
</manifest>
Output:
Step1:N
owruntheAppinEmulator.Youwillseethebelowoutputscreen
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
421
Step2:Filltheemail,passwordandclickonremembermecheckbox.Inourcasewehavefilled
info@abhiandroid.comandabhiandroid.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
422
Step3:ItwilldisplayyouthewelcomemessagealongwithyouremailID.NowclosetheApp
andreopenit.YouwillseethesamemessageofWelcomeandyouremailaddressprinted.So
herewehavestoredyouremailaddressonyourdeviceitselfusingSharedPreference.
Importance:
Duringapplicationdevelopmenttherearemanysituationwhereweneedtostoreorsavesome
datainafile.Soratherthancreatingyourownfileandthenmanagingit,Androidprovides
mechanismtosavedatausingSharedPreferences.Tosavesomelittleamountofdata
SharedPreferencescanbeusedlikeusernameandpasswordofuser,Howeverifthereisneedto
savelargeamountofdatathealwaysprefertosavedatausingsqlite.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
423
Sqlite
SQLiteisaStructurequerybasedatabase,opensource,lightweight,nonetworkaccessand
standalonedatabase.Itsupportembeddedrelationaldatabasefeatures.
Wheneveranapplicationneedstostorelargeamountofdatathenusingsqliteismore
preferablethanotherrepositorysystemlikeSharedPreferencesorsavingdatainfiles.
AndroidhasbuiltinSQLitedatabaseimplementation.Itisavailablelocallyoverthe
device(mobile&tablet)andcontaindataintextformat.Itcarrylightweightdataandsuitable
withmanylanguages.So,itdoesn’trequiredanyadministrationorsetupprocedureofthe
database.
ImportantNote–T
hedatabasecreatedissavedinadirectory:
data/data/APP_Name/databases/DATABASE_NAME.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
424
CreatingAndUpdatingDatabaseInAndroid
Forcreating,updatingandotheroperationsyouneedtocreateasubclassorSQLiteOpenHelper
class.SQLiteOpenHelperisahelperclasstomanagedatabasecreationandversion
management.ItprovidestwomethodsonCreate(SQLiteDatabasedb),
onUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion).
TheSQLiteOpenHelperisresponsibleforopeningdatabaseifexist,creatingdatabaseifitdoes
notexistsandupgradingifrequired.TheSQLiteOpenHelperonlyrequiretheDATABASE_NAME
tocreatedatabase.AfterextendingSQLiteOpenHelperyouwillneedtoimplementitsmethods
onCreate,onUpgradeandconstructor.
onCreate(SQLiteDatabasesqLiteDatabase)methodiscalledonlyoncethroughoutthe
applicationlifecycle.ItwillbecalledwheneverthereisafirstcalltogetReadableDatabase()or
getWritableDatabase()functionavailableinsuperSQLiteOpenHelperclass.So
SQLiteOpenHelperclasscalltheonCreate()methodaftercreatingdatabaseandinstantiate
SQLiteDatabaseobject.Databasenameispassedinconstructorcall.
onUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion)isonlycalledwhenever
thereisaupdationinexistingversion.Sotoupdateaversionwehavetoincrementthevalueof
versionvariablepassedinthesuperclassconstructor.
InonUpgrademethodwecanwritequeriestoperformwhateveractionisrequired.Inmost
exampleyouwillseethatexistingtable(s)arebeingdroppedandagainonCreate()methodis
beingcalledtocreatetablesagain.Butit’snotmandatorytodosoanditalldependsuponyour
requirements.
Wehavetochangedatabaseversionifwehaveaddedanewrowinthedatabasetable.Ifwe
haverequirementthatwedon’twanttoloseexistingdatainthetablethenwecanwritealter
tablequeryintheonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion)method.
Formoredetailsread:I nsert,Read,Delete&UpdateOperationInSQLite
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
425
SQLiteExampleInAndroidStudio
GetBetterUnderstandingofSqliteBeforeYouReadExample–Togetbetterunderstandingof
SQlitedatabase,itisrecommendedyoureadbelowarticlefirst:
● IntroductionToSQLiteAndInstallation
● ListOfAllOperatorsInSQLite
● DataTypeAndCommandsInSQLite
● ListOfAllClausesInSQLiteForDefiningSpecificCondition
● Insert,Read,Delete&UpdateOperationInSQLite
Inthisexamplewesimplywanttoillustratetheinsert,update,deleteandmoreoperationsof
SQLiteoveratableinAndroidStudi.Wecreatedaactivityhavingtextview,buttonandedittext
overit.AnotherclasswhichextendsSQLiteOpenHelperwherethecreateandinsertoperations
willbecarriedout.Theexamplecontainpropervalidationlikeyouneedtoenterdatabefore
executinganyoperation.
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanation:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
426
Step1:C
reateaNewProjectandNameitSQLiteOperations.
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepwecreatealayoutinourXMLfileaddingtextbox,buttons,edittext.Onbutton
onclickisdefinedwhichassociateitwithrelatedfunction.
<?
xml
version
="
1.0"
encoding ="
utf-8" ?>
<RelativeLayoutxmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:id
="
@+id/activity_main"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
="
com.example.sqliteoperations.MainActivity"
android:background
="
@android:color/holo_blue_dark" >
<TextView
android:text
="
@string/username"
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
android:layout_alignParentTop
="
true"
android:layout_marginTop
="
12dp"
android:id
="
@+id/textView"
android:textSize
="
18sp"
android:textStyle
="bold|italic"
android:layout_alignParentLeft
="true"
android:layout_alignParentStart
="true"
android:gravity
="center" />
<EditText
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
android:inputType
="textPersonName"
android:ems
="10"
android:id
="
@+id/editName"
android:textStyle
="bold|italic"
android:layout_below
="
@+id/textView"
android:layout_alignParentRight
="true"
android:layout_alignParentEnd
="
true"
android:hint
="
Enter Name"
android:gravity
="center_vertical|center" /
>
<TextView
android:text
="
@string/password"
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
android:layout_marginTop
="
13dp"
android:id
="
@+id/textView2"
android:textStyle
="bold|italic"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
427
ndroid:textSize
a ="18sp"
android:layout_below
="
@+id/editName"
android:layout_alignParentRight
="
true"
android:layout_alignParentEnd
="
true"
android:gravity
="
center"
android:hint
="EnterPassword"
/
>
<Button
android:text
="
@string/view_data"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:id
="
@+id/button2"
android:textSize
="18sp"
android:onClick
="
viewdata"
android:textStyle
="
bold|italic"
android:layout_alignBaseline
="
@+id/button"
android:layout_alignBottom
="
@+id/button"
android:layout_alignRight
="@+id/button4"
android:layout_alignEnd
="@+id/button4" /
>
<Button
android:text
="
@string/add_user"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:id
="
@+id/button"
android:textStyle
="
bold|italic"
android:textSize
="18sp"
android:onClick
="
addUser"
android:layout_marginLeft
="28dp"
android:layout_marginStart
="
28dp"
android:layout_below
="
@+id/editPass"
android:layout_alignParentLeft
="
true"
android:layout_alignParentStart
="true"
android:layout_marginTop
="
23dp"/>
<Button
android:text
="
@string/update"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:id
="
@+id/button3"
android:onClick
="
update"
android:textStyle
="
normal|bold"
android:layout_below
="
@+id/editText3"
android:layout_alignLeft
="@+id/button4"
android:layout_alignStart
="
@+id/button4"
android:layout_marginTop
="13dp"
/>
<EditText
android:layout_width
="wrap_content"
android:layout_height
="
wrap_content"
android:inputType
="
textPersonName"
android:ems
="10"
android:id
="
@+id/editText6"
android:layout_alignTop
="
@+id/button4"
android:layout_alignParentLeft
="
true"
android:layout_alignParentStart
="true"
android:freezesText
="
false"
android:hint
="
EnterName toDelete Data"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
428
ndroid:layout_toLeftOf
a ="
@+id/button2"
android:layout_toStartOf
="@+id/button2"/
>
<Button
android:text
="
@string/delete"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_marginRight
="
21dp"
android:layout_marginEnd
="21dp"
android:id
="
@+id/button4"
android:onClick
="
delete"
android:textStyle
="
normal|bold"
tools:ignore
="
RelativeOverlap"
android:layout_marginBottom
="41dp"
android:layout_alignParentBottom
="
true"
android:layout_alignParentRight
="true"
android:layout_alignParentEnd
="
true" /
>
<EditText
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:inputType
="
textPersonName"
android:ems
="10"
android:layout_marginTop
="
47dp"
android:id
="
@+id/editText3"
android:textStyle
="
bold|italic"
android:textSize
="14sp"
android:layout_below
="
@+id/button"
android:layout_alignParentLeft
="true"
android:layout_alignParentStart
="true"
android:layout_marginLeft
="7dp"
android:layout_marginStart
="7dp"
android:hint
="
Current Name" />
<EditText
android:layout_width
="match_parent"
android:layout_height
="
wrap_content"
android:inputType
="
textPassword"
android:ems
="10"
android:layout_marginTop
="
11dp"
android:id
="
@+id/editPass"
android:hint
="
EnterPassword"
android:gravity
="
center_vertical|center"
android:textSize
="18sp"
android:layout_below
="@+id/textView2"
android:layout_alignParentLeft
="
true"
android:layout_alignParentStart
="true"
android:textAllCaps
="
false"
android:textStyle
="
normal|bold" />
<EditText
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:inputType
="
textPersonName"
android:ems
="10"
android:id
="
@+id/editText5"
android:textStyle
="
bold|italic"
android:textSize
="14sp"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
429
ndroid:hint
a ="New
Name"
android:layout_alignTop
="@+id/button3"
android:layout_alignLeft
="
@+id/editText3"
android:layout_alignStart
="@+id/editText3"
android:layout_marginTop
="
32dp"/
>
</RelativeLayout>
Step3:N
owopenapp->java->package->MainActivity.javaandaddthebelowcode.
Inthisstepweusedthefunctionsthatlinkedviathebuttonclick.Thesefunctionsaredefined
inotherclassandareusedhere.Eachfunctionreturnvaluethatdefinenoofrowsupdated,
usingthatwedefinedwhetheroperationissuccessfulornot.Alsouserneedtodefinevaliddata
toperformoperationemptyfieldswillnotbeentertainedandreturnerror.
packagecom.e
xample .sqliteoperations ;
import
android .s
upport .v
7.a
pp.AppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .V
iew ;
import
android .w
idget .EditText ;
publicc
lass MainActivity extends A
ppCompatActivity {
EditText
Name,Pass,updateold ,
updatenew ,delete ;
m
yDbAdapter helper ;
@Override
protected
voidonCreate (B
undle savedInstanceState ){
super
.onCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .activity_main );
Name
=(E
ditText )findViewById (R.
id
.editName );
Pass
=(E
ditText )findViewById (R.
id
.editPass );
u
pdateold =(E
ditText )findViewById (R
.i
d.e
ditText3 );
u
pdatenew =(E
ditText )findViewById (R
.i
d.e
ditText5 );
delete
=
(E
ditText )findViewById (R
.i
d.e
ditText6 );
h
elper= new
myDbAdapter (this);
}
public
v
oid addUser (Viewview)
{
String
t1=Name .g
etText ().toString ();
String
t2=Pass .g
etText ().toString ();
if
(t
1.isEmpty ()|
|t2
.isEmpty ())
{
Message .m
essage (g
etApplicationContext (),
"Enter Both
Name
and
Password"
);
}
else
{
long
id=helper .insertData (t1
,t2);
if(i
d<=
0)
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
430
essage
M .m
essage
(g
etApplicationContext
(),
"Insertion
Unsuccessful"
);
Name
.setText
("
"
);
Pass
.setText
("
"
);
}else
{
Message
.m
essage
(g
etApplicationContext
(),
"Insertion
Successful"
);
Name
.setText
("
"
);
Pass
.setText
("
"
);
}
}
}
ublic
p v
oid
viewdata
(View
view
)
{
String
data=
helper.g
etData();
Message
.message
(t
his,d
ata);
}
ublic
p v
oid update (Viewview
)
{
String
u1= updateold .g
etText().
toString ();
String
u2= updatenew .g
etText().
toString ();
if
(u
1.isEmpty ()
|
|
u2.isEmpty())
{
Message .message (g
etApplicationContext (),"Enter
Data"
);
}
else
{
inta=
helper .u
pdateName (
u1
,u2
);
if(a
<=
0)
{
Message
.message (g
etApplicationContext (),
"Unsuccessful"
);
u
pdateold .s
etText ("
"
);
u
pdatenew .s
etText ("
"
);
}else {
Message
.message (g
etApplicationContext (),
"Updated"
);
u
pdateold .s
etText ("
"
);
u
pdatenew .s
etText ("
"
);
}
}
}
public
v
oid delete (Viewview)
{
String
uname= d
elete .getText().
toString
();
if
(u
name .isEmpty ())
{
Message .m
essage (g
etApplicationContext (),"Enter
Data"
);
}
else
{
inta=
helper .d
elete (uname
);
if(a
<=
0)
{
Message
.message (getApplicationContext (),
"Unsuccessful"
);
delete
.s
etText ("
");
}
else
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
431
essage
M .message
(this,"
DELETED"
);
delete
.s
etText("
");
}
}
}
}
Step4:I nthisstepcreateajavaclassmyDbAdapter.java.
Inthiswedefinethefunctionsthatareusedtoperformtheoperationsinsert,updateanddelete
operationsinSQLite.Furtherthisclasscreateanotherclassthatwillextendthe
SQLiteOpenHelper.Eachfunctioncarryequivalentmethodsthatperformoperations.
ImportantNote–A
ccordingtonamingconventionitissuggestedtodefineprimarykey
startingwithunderscoreexample:_id.
packagecom
.e
xample .s
qliteoperations ;
import
android .c
ontent .C
ontentValues ;
import
android .c
ontent .C
ontext ;
import
android .d
atabase .C
ursor ;
import
android .d
atabase .s
qlite .SQLiteDatabase ;
import
android .d
atabase .s
qlite .SQLiteOpenHelper ;
publicc
lassmyDbAdapter{
m
yDbHelper myhelper ;
public
myDbAdapter (Context
context )
{
m
yhelper= newmyDbHelper (context );
}
public
l
onginsertData (S
tring name,String p
ass )
{
SQLiteDatabase
dbb=myhelper .getWritableDatabase ();
ContentValues
contentValues= newC
ontentValues ();
c
ontentValues .p
ut(myDbHelper .N
AME ,name
);
c
ontentValues .p
ut(myDbHelper .M
yPASSWORD ,p ass);
long
id=dbb.i
nsert (m
yDbHelper .TABLE_NAME ,n
ull ,
contentValues);
return
id
;
}
public
S
tring
getData ()
{
SQLiteDatabase
db=myhelper .g
etWritableDatabase ();
String
[]
columns= {
myDbHelper .UID,m
yDbHelper .NAME,m
yDbHelper.M
yPASSWORD};
Cursor
cursor= db
.query (m
yDbHelper .TABLE_NAME ,c
olumns ,n
ull
,n
ull,n
ull
,n
ull
,null
);
StringBuffer
buffer =new S
tringBuffer ();
while
(
c
ursor .m
oveToNext ())
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
432
{
intcid= c
ursor .g
etInt (cursor .g
etColumnIndex (m
yDbHelper .UID));
String
name= c
ursor .g
etString (c
ursor .getColumnIndex (myDbHelper .NAME ));
String password
=
cursor .g
etString (cursor .getColumnIndex (m
yDbHelper .M
yPASSWORD ));
b
uffer .a
ppend (cid
+" "+name+ " "+
password+ "\n");
}
return
buffer .toString ();
}
public
intdelete (String uname )
{
SQLiteDatabase
db=
myhelper .g
etWritableDatabase ();
String
[]
whereArgs= {
uname };
int
count= d
b.d
elete (m
yDbHelper .T
ABLE_NAME, myDbHelper .N
AME +"
= ?"
,whereArgs );
return
count ;
}
public
i
nt
updateName (S
tring oldName, String newName )
{
SQLiteDatabase
db=
myhelper .g
etWritableDatabase ();
ContentValues
contentValues= newC
ontentValues ();
c
ontentValues .put(myDbHelper .N
AME ,n
ewName );
String
[]
whereArgs ={oldName };
int
count= d
b.u
pdate (m
yDbHelper .T
ABLE_NAME ,c
ontentValues ,myDbHelper .NAME+"
=
?"
,w
hereArgs) ;
return
count ;
}
static
c
lass
myDbHelpere xtends SQLiteOpenHelper
{
private
static f
inal String DATABASE_NAME= "myDatabase" ;
// Database Name
private
static f
inal String TABLE_NAME ="myTable" ; / / Table Name
private
static f
inal int
DATABASE_Version= 1;
. /
/Database Version
private
static f
inal String UID="
_id" ; /
/ Column I
(Primary Key)
private
static f
inal String NAME= "Name" ;
//Column II
private
static f
inal String MyPASSWORD ="Password" ;
// Column III
private
static f
inal String CREATE_TABLE= "
CREATE TABLE "+
TABLE_NAME +
"
("+U
ID +"
INTEGER PRIMARY KEY AUTOINCREMENT, "+
NAME +"
VARCHAR(255) ,"+
MyPASSWORD +"
VARCHAR(225));" ;
private
static f
inal String DROP_TABLE ="
DROP TABLE IF
EXISTS "+
TABLE_NAME ;
private
Context context ;
public
myDbHelper (Context context ){
super (context ,DATABASE_NAME ,null ,DATABASE_Version );
this .context =c
ontext ;
}
public
v
oid onCreate (SQLiteDatabase
db){
try{
d
b.e
xecSQL (CREATE_TABLE );
}catch (E
xception
e){
Message
.message (c
ontext ,"
"+e)
;
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
433
Override
@
public
v
oid onUpgrade(SQLiteDatabase
db,i
nt
oldVersion
,i
nt
newVersion
){
try{
Message
.m
essage (context
,"OnUpgrade" );
d
b.e
xecSQL (D
ROP_TABLE );
o
nCreate (db
);
}catch (
Exceptione)
{
Message
.m
essage (context
,""
+e
);
}
}
}
}
Step5:InthisstepcreateanotherjavaclassMessage.class
Inthisjustsimplyaddtoastfordisplayingmessage.Thisisoptional,itisjustaddedtoagain
andagaindefiningtoastintheexample.
packagecom
.e
xample.s
qliteoperations ;
import
android .c
ontent.Context
;
import
android .w
idget.T
oast;
publicc
lassM
essage{
public
s
taticv
oidmessage
(Context
context
,String
message
){
Toast
.m
akeText(context
,message,T
oast
.L
ENGTH_LONG).
show
();
}
}
Output
Nowruntheappandviewthefunctionalityaddedoverthebuttons.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
434
Add&RetrieveImageFromSQLiteDatabase:
Tounderstandhowtoaddorretrieveimagefromphoneexternalstoragetoapplicationusing
SQLiteDatabase.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
435
JSONParsing
JSONstandsforJavaScriptObjectNotation.Itisstructured,lightweight,humanreadableand
easytoparse.It’sabestalternativetoXMLwhenourandroidappneedstointerchangedata
fromserver.XMLparsingisverycomplexascomparetoJSONparsing.
JSONisshorter,quickerandeasierwaytointerchangedatafromserver.JSONisgreatsuccess
andmostoftheAPIavailablesupportJSONformat.
AndroidProvideusfourdifferentclassestomanipulateJSONdata.Theseclassesare
JSONObject,JSONArray,JSONStringerandJSONTokenizer.
SampleJSONformat:
BelowisthesamplecodeofJSON.ItsverysimpleJSONcodewhichgivesusthelistofusers
whereeachobjectcontaintheinformationlikeuserid,name,email,genderanddifferent
contactnumbers.
{
"users"
:[
{
id"
" :"
1087",
"name"
:"
Abhishek Saini",
"email"
:"info@abhiandroid.com" ,
"gender"
:"
male" ,
"contact"
:{
"mobile" :"+910000000000"
,
"home":"00000000",
"office" :"00
000000"
}
,
}
{
id"
" :"
1088",
"name"
:"
Gourav" ,
"email"
:"gourav9188@gmail.com" ,
"gender"
:"
male" ,
"contact"
:{
"mobile" :"+910000000000"
,
"home":"00000000",
"office" :"00000000"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
436
}
,
}
.
.
.
.
]
}
JSONElementsInAndroid:
InAndroid,JSONconsistofmanycomponents.Belowwedefinesomecommoncomponents.
Array([): I naJSON,squarebracket([)representsaJSONArray.JSONArrayvaluesmaybeany
mixofJSONObjects,otherJSONArrays,Strings,Booleans,Integers,Longs,Doubles,nullor
NULL.ValuesmaynotbeNaNs,infinities,orofanytypenotlistedhere.
Objects({):InaJSON,curlybracket({)representsaJSONObject.AJSONObjectrepresentsthe
dataintheformofkeyandvaluepair.JSONObjectvaluesmaybeanymixofotherJSONObjects,
JSONArrays,Strings,Booleans,Integers,Longs,Doubles,nullorNULL.Valuesmaynotbe
NaNs,infinities,orofanytypenotlistedhere.
ey: A
K JSONObjectcontainsakeythatisinstringformat.Apairofkeyandvaluecreatesa
JSONObject.
achkeyhasavaluethatcouldbeprimitivedatatype(integer,float,Stringetc).
Value:E
JSONParsingInAndroid:
sually,JSONcontaintwotypesofnodesJSONArrayandJSONObjectsowhileparsingwehave
U
tousetheappropriatemethod.IfJSONstartsfromsquarebracket([)weusegetJSONArray()
methodandifitstartfromcurlybracket({)thenweshouldusethegetJSONObject()method.
ApartfromthesetherearesomeothermethodsforbetterparsingJSONdata.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
437
JSONObjetParsingmethods:
BelowwedefinesomeimportantmethodsofJSONObjectparsingwhicharemainlyusedfor
parsingthedatafromJSONObject.
1.get(Stringname):T
hismethodisusedtogetthevaluefromJSONObject.Itreturnsthe
valueofobjecttype.WepasstheStringtypekeyanditreturnsthevalueofObjecttypeifexists
otherwiseitthrowsJSONException.
2.getBoolean(Stringname): T
hismethodisusedtogettheBooleanvaluefrom
JSONObject.WepasstheStringtypekeyanditreturnsthevalueofBooleantypeifexists
otherwiseitthrowsJSONException.
3.getDouble(Stringname):T
hismethodisusedtogetthedoubletypevaluefrom
JSONObject.WepasstheStringtypekeyanditreturnsthevalueindoubletypeifexists
otherwiseitthrowsJSONException.
4.getInt(Stringname): T
hismethodisusedtogettheinttypevaluefromJSONObject.We
passthestringtypekeyanditreturnsthevalueininttypeifexistsotherwiseitthrows
JSONException.
5.getJSONArray(Stringname):T
hismethodisusedtogettheJSONArraytypevalue.We
passtheStringtypekeyanditreturnsJSONArrayifexistsotherwiseitthrowsJSONException.
6.getJSONObject(Stringname):T
hismethodisusedtogettheJSONObjecttypevalue.We
passtheStringtypekeyanditreturnstheJSONObjectvalueifexistsotherwiseitthrows
JSONException.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
438
7.getLong(Stringname):T
hismethodisusedtogetthelongtypevaluefromJSONObject.
WepasstheStringtypekeyanditreturnsthevalueinlongtypeifexistsotherwiseitthrows
JSONException.
8.getString(Stringname):T
hismethodisusedtogettheStringtypevaluefrom
JSONObject.WepasstheStringtypekeyanditreturnsthevalueinStringtypeifexists
otherwiseitthrowsJSONException.
9.length():T
hismethodisusedtogetthenumberofname/valuemappingsinthisobject.
10.keys():T
hismethodisusedtogettheiteratorofStringnamesintheObject.
11.opt(Stringname):T
hismethodisusedtogetthevaluefromJSONObject.Itreturnsthe
valueofObjecttype.WepasstheStringtypekeyanditreturnsthevalueofObjecttypeifexists
otherwiseitreturnsnull.
12.optBoolean(Stringname):T
hismethodisusedtogettheBooleanvaluefrom
JSONObject.WepasstheStringtypekeyanditreturnsthevalueofBooleantypeifexists
otherwiseitreturnsfalse.
13.optDouble(Stringname):T
hismethodisusedtogetthedoubletypevaluefrom
JSONObject.WepasstheStringtypekeyanditreturnsthevalueindoubletypeifexists
otherwiseitreturnsNaN.
14.optInt(Stringname):T hismethodisusedtogettheinttypevaluefromJSONObject.We
passthestringtypekeyanditreturnsthevalueininttypeifexistsotherwiseitreturns0.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
439
15.optJSONArray(Stringname):T
hismethodisusedtogettheJSONArraytypevalue
fromJSONObject.WepasstheStringtypekeyanditreturnsJSONArrayifexistsotherwiseit
returnsnull.
16.optJSONObject(Stringname):T
hismethodisusedtogettheotherJSONObjecttype
valuefromJSONObject.WepasstheStringtypekeyanditreturnstheJSONObjectvalueif
existsotherwiseitreturnsnull.
17.optLong(Stringname):T
hismethodisusedtogetthelongtypevaluefromJSONObject.
WepasstheStringtypekeyanditreturnsthevalueinlongtypeifexistsotherwiseitreturns0.
18.optString(Stringname):T
hismethodisusedtogettheStringtypevaluefrom
JSONObject.WepasstheStringtypekeyanditreturnsthevalueinStringtypeifexists
otherwiseitreturnsempty(“”)string.
JSONArrayParsingmethods:
BelowwedefinesomeimportantmethodsofJSONArrayparsingwhicharemainlyusedfor
parsingthedatafromJSONArray.
1.get(intindex):T
hismethodisusedtogetthevaluefromJSONArray.Itreturnsthevalue
ofobjecttype.Wepasstheindexanditreturnsthevalueofobjecttypeifexistotherwiseit
throwsJSONException.
2.getBoolean(intindex):ThismethodisusedtogettheBooleanvaluefromJSONArray.We
passtheindexanditreturnsthevalueofBooleantypeifexistsotherwiseitthrows
JSONException.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
440
3.getDouble(intindex):T
hismethodisusedtogetthedoubletypevaluefromJSONArray.
Wepasstheindexanditreturnsthevalueindoubletypeifexistsotherwiseitthrows
JSONException.
4.getInt(intindex):ThismethodisusedtogettheinttypevaluefromJSONArray.Wepass
theindexanditreturnsthevalueininttypeifexistsotherwiseitthrowsJSONException.
5.getJSONArray(intindex):ThismethodisusedtogettheJSONArraytypevalue.Wepass
theindexanditreturnsJSONArrayifexistsotherwiseitthrowsJSONException.
6.getJSONObject(intindex):T
hismethodisusedtogettheJSONObjecttypevalue.We
passtheindexanditreturnstheJSONObjectvalueifexistsotherwiseitthrowsJSONException.
7.getLong(intindex):T
hismethodisusedtogetthelongtypevaluefromJSONArray.We
passtheindexanditreturnsthevalueinlongtypeifexistsotherwiseitthrowsJSONException.
8.getString(intindex):ThismethodisusedtogettheStringtypevaluefromJSONArray.We
passtheindexanditreturnsthevalueinStringtypeifexistsotherwiseitthrows
JSONException.
9.length():ThismethodisusedtogetthenumberofvaluesinthisArray.
10.opt(intindex):ThismethodisusedtogetthevaluefromJSONArray.Itreturnsthevalue
ofObjecttype.WepasstheindexanditreturnsthevalueatindexofObjecttypeifexists
otherwiseitreturnsnull.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
441
11.optBoolean(intindex):T
hismethodisusedtogettheBooleanvaluefromJSONArray.
WepasstheindexanditreturnsthevalueofBooleantypeifexistsotherwiseitreturnsfalse.
12.optDouble(intindex):T
hismethodisusedtogetthedoubletypevaluefromJSONArray.
WepasstheindexanditreturnsthevalueindoubletypeifexistsotherwiseitreturnsNaN.
13.optInt(intindex):T
hismethodisusedtogettheinttypevaluefromJSONArray.Wepass
theindexanditreturnsthevalueininttypeifexistsotherwiseitreturns0.
14.optJSONArray(intindex):T
hismethodisusedtogettheotherJSONArraytypevalue
fromJSONArray.WepasstheindexanditreturnsJSONArrayifexistsotherwiseitreturnsnull.
15.optJSONObject(intindex):T
hismethodisusedtogettheJSONObjecttypevaluefrom
JSONArray.WepasstheindexanditreturnstheJSONObjectvalueifexistsotherwiseitreturns
null.
16.optLong(intindex):T
hismethodisusedtogetthelongtypevaluefromJSONArray.We
passtheindexanditreturnsthevalueinlongtypeifexistsotherwiseitreturns0.
17.optString(intindex):ThismethodisusedtogettheStringtypevaluefromJSONArray.
WepasstheindexanditreturnsthevalueinStringtypeifexistsotherwiseitreturnsempty(“”)
string.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
442
Example1ofSimpleJSONParsingInAndroidStudio:
BelowistheexampleofJSONparsinginAndroid,InthisexampleweparsethedatafromJSON
andthendisplayitintheUI.Inthis,wehaveemployeenameandsalarystoredinJSONformat.
FirstlywecreatetwoTextView‘sinourXMLfileandtheninourActivityweparsethedatausing
JSONObjectmethodsandsetitintheTextView‘s.
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanationoftheexample:
Step1:CreateanewprojectandnameitJSONParsingExample.
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
443
InthisstepwecreatetwoTextView’sfordisplayingemployeenameandsalary.
<?
xml
version
="
1.0"
encoding ="utf-8" ?>
<RelativeLayoutx
mlns: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 ="abhiandroid.com.jsonparsingexample.MainActivity" >
<TextView
android:id
="@+id/name"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_centerHorizontal
="
true"
android:layout_marginTop
="50dp"
android:text
="Name"
android:textColor
="#000"
android:textSize
="
20sp" /
>
<TextView
android:id
="@+id/salary"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_centerHorizontal
="
true"
android:layout_marginTop
="80dp"
android:text
="Salary"
android:textColor
="#000"
android:textSize
="
20sp" /
>
</RelativeLayout>
Step3:N
owopenapp->java->package->MainActivity.javaandaddthebelowcode.
InthisstepfirstlywegetthereferenceofbothTextView’sthenweparsetheJSONusing
JSONObjectmethodsandfinallywesetthedatainTextview’s.
package
abhiandroid .c
om
.jsonparsingexample ;
import
android .o
s.B
undle ;
import
android .s
upport .v
7.app
.A
ppCompatActivity;
import
android .w
idget .T
extView ;
import
org.j
son.JSONException ;
import
org.j
son.JSONObject ;
public
c
lassMainActivity extendsA
ppCompatActivity
{
String
JSON_STRING= "
{\"employee\":{\"name\":\"Abhishek
Saini\",\"salary\":65000}}"
;
String
name,salary;
TextView
employeeName ,employeeSalary;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
444
Override
@
protected
v
oid
onCreate (B
undle
savedInstanceState ){
super
.o
nCreate(s
avedInstanceState );
s
etContentView(R
.l
ayout .a
ctivity_main
);
//
getthe
reference of
TextView's
e
mployeeName=(
TextView )
findViewById(R
.i
d.name);
e
mployeeSalary=(TextView)
findViewById (R
.i
d.s
alary);
try
{
//get
JSONObject fromJSONfile
JSONObject
obj=new
J
SONObject (JSON_STRING );
//fetch
JSONObject named employee
JSONObject
employee= obj
.g
etJSONObject ("
employee"
);
//get
employee nameand
salary
name=
employee .getString("
name" );
salary=
employee .g
etString ("
salary" );
//set
employee nameand
salary inTextView's
employeeName .s
etText("Name:"+n
ame );
employeeSalary .s
etText ("
Salary: "+s
alary );
}c
atch(
J
SONException
e){
e
.p
rintStackTrace
();
}
}
}
JSONParsingFileExample2InAndroidStudio:
Belowisthe2ndexampleofJSONparsingInAndroidStudio.InthisexamplewecreateaJSON
fileandstoreitinassetsfolderofAndroid.InthisJSONfilewehavelistofuserswhereeach
objectcontaintheinformationlikeuserid,name,email,genderanddifferentcontactnumbers.
InthisweareusingLinearLayoutManagerwithverticalorientationtodisplaythearrayitems.
FirstlywedeclareaRecyclerViewinourXMLfileandthengetthereferenceofitinourActivity.
AfterthatwefetchtheJSONfilethenparsetheJSONArraydataandfinallysettheAdapterto
showtheitemsinRecyclerView.WheneverauserclicksonanitemthenameofthePersonis
displayedonthescreenwiththehelpofToast.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
445
Step1:C
reateanewprojectandnameitJSONParsingExample.
Step2:O
penGradleScripts>build.gradleandaddRecyclerViewandCardViewLibrary
dependencyinit.
applyplugin:'
com.android.application'
android{
c
ompileSdkVersion2 4
b
uildToolsVersion" 24.0.1"
d
efaultConfig{
a
pplicationId" abhiandroid.com.jsonparsingexample"
m
inSdkVersion1 6
t
argetSdkVersion2 4
v
ersionCode 1
v
ersionName "1.0"
}
b
uildTypes{
r
elease{
m
inifyEnabledf alse
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
446
p
roguardFilesgetDefaultProguardFile('
proguard-android.txt' ),
'proguard-rules.pro'
}
}
}
dependencies{
c
ompile fileTree(d
ir
:'
libs'
,
include
:[
'*.jar'
])
t
estCompile' junit:junit:4.12'
c
ompile 'com.android.support:appcompat-v7:24.1.1'
c
ompile "com.android.support:recyclerview-v7:23.0.1" //
dependency
filefor
RecyclerView
c
ompile 'com.android.support:cardview-v7:23.0.1' /
/
dependencyfilefor
CardView
}
Step3:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepwecreateaRecyclerViewinourXMLfile.
Step4:C
reateanewXMLfilerowlayout.xmlforitemofRecyclerViewandpastethefollowing
codeinit.
InthisstepwecreateanewxmlfileforitemrowinwhichwecreateaTextViewtoshowthe
data.
<?
xml
version="
1.0"
encoding ="
utf-8" ?>
<android.support.v7.widget.CardView
xmlns:android="
http://schemas.android.com/apk/res/android"
xmlns:card_view
="
http://schemas.android.com/apk/res-auto"
xmlns:tools
="
http://schemas.android.com/tools"
android:id
="@+id/card_view"
android:layout_width
="
match_parent"
android:layout_margin
="5dp"
android:layout_height
="wrap_content" >
<LinearLayout
android:layout_width
="match_parent"
android:layout_height
="
wrap_content"
android:orientation
="
vertical"
android:padding
="10dp" >
<!--
i
temsfor a
single row ofRecyclerView
-
->
<TextView
android:id ="
@+id/name"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:text ="
Name"
android:textColor ="
#000"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
447
android:textSize
="
20sp"
/
>
<TextView
android:id
="
@+id/email"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:text="
email@email.com"
android:textColor="#000"
android:textSize="
15sp" />
<TextView
android:id
="
@+id/mobileNo"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:text="
e9999999999"
android:textColor="#000"
android:textSize="
15sp" /
>
</LinearLayout>
</android.support.v7.widget.CardView>
Step5:N
owopenapp->java->package->MainActivity.javaandaddthebelowcode.
InthisstepfirstlywegetthereferenceofRecyclerView.AfterthatwefetchtheJSONfilefrom
assetsandparsetheJSONdatausingJSONArrayandJSONObjectmethodsandthenseta
LayoutManagerandfinallywesettheAdaptertoshowtheitemsinRecyclerView.
package
abhiandroid .c
om.jsonparsingexample ;
import
android .o
s.B
undle ;
import
android .s
upport .v
7.a
pp .A
ppCompatActivity ;
import
android .s
upport .v
7.w
idget .L
inearLayoutManager ;
import
android .s
upport .v
7.w
idget .R
ecyclerView ;
import
android .u
til .L
og;
import
org.j
son.JSONArray ;
import
org.j
son.JSONException ;
import
org.j
son.JSONObject ;
import
java.i
o.I
OException ;
import
java.i
o.I
nputStream ;
import
java.u
til .A
rrayList ;
import
java.u
til .A
rrays ;
public
c
lassM
ainActivity extends AppCompatActivity {
//
ArrayList for person names, email Id'sandmobile numbers
ArrayList
<S
tring >personNames= n
ew A
rrayList <>();
ArrayList
<S
tring >emailIds= n
ewArrayList <>();
ArrayList
<S
tring >mobileNumbers= n
ew A
rrayList <>();
@Override
protected
v
oid
onCreate (Bundle
savedInstanceState ){
super
.o
nCreate (s
avedInstanceState );
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
448
s
etContentView (R
.layout .a
ctivity_main );
//
get the reference of RecyclerView
RecyclerView
recyclerView= (R
ecyclerView )findViewById (R.
id
.recyclerView );
//
set aLinearLayoutManager with default vertical orientation
LinearLayoutManager
linearLayoutManager= n
ew
LinearLayoutManager (g
etApplicationContext ());
r
ecyclerView .setLayoutManager (linearLayoutManager );
try
{
// get JSONObject from JSON file
JSONObject
obj= new J
SONObject (l
oadJSONFromAsset ());
// fetch JSONArray named users
JSONArray
userArray= obj.getJSONArray ("users");
// implement for loop for getting users listdata
for (
i
nt
i=0;
i<
userArray .l
ength ();i+
+)
{
//
create a
JSONObject for fetching single user data
JSONObject
userDetail =userArray .g
etJSONObject (i)
;
//
fetch email and name and store itinarraylist
p
ersonNames .add(u
serDetail .getString ("
name" ));
e
mailIds .add(u
serDetail .getString ("
email" ));
//
create a
object for getting contact data from JSONObject
JSONObject
contact= userDetail .getJSONObject ("
contact" );
//
fetch mobile number and store itin
arraylist
m
obileNumbers .add(contact .g
etString ("mobile" ));
}
}c
atch (J
SONException
e){
e
.p
rintStackTrace ();
}
// c
all the constructor of CustomAdapter tosendthe reference and data
toAdapter
CustomAdapter
customAdapter= newC
ustomAdapter (M
ainActivity .this
,
personNames ,
emailIds,mobileNumbers );
r
ecyclerView .setAdapter (customAdapter );//set
the Adapter toRecyclerView
}
public
S
tring
loadJSONFromAsset (){
String
json= null ;
try
{
InputStream i
s=
getAssets (). open ("
users_list.json" );
int
size= i
s.available ();
byte []buffer= newb
yte [s
ize ];
is.r
ead (b
uffer );
is.c
lose ();
j
son= newS
tring (buffer ,"UTF-8" );
}c
atch (I
OException
ex){
e
x.p
rintStackTrace ();
return null;
}
return
json ;
}
}
Step6:C
reateanewclassCustomAdapter.javainsidepackageandaddthefollowingcode.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
449
InthisstepwecreateaCustomAdapterclassandextendsRecyclerView.Adapterclasswith
ViewHolderinit.Afterthatweimplementtheoverridedmethodsandcreateaconstructorfor
gettingthedatafromActivity,InthiscustomAdaptertwomethodsaremoreimportantfirstis
onCreateViewHolderinwhichweinflatethelayoutitemxmlandpassittoViewHolderand
otherisonBindViewHolderinwhichwesetthedataintheview’swiththehelpofViewHolder.
packageabhiandroid .c
om .j
sonparsingexample ;
import
android .content .Context ;
import
android .support .v7
.widget .RecyclerView ;
import
android .view .L
ayoutInflater ;
import
android .view .V
iew ;
import
android .view .V
iewGroup ;
import
android .widget .TextView ;
import
android .widget .Toast ;
import
java.util .A
rrayList ;
publicc
lass C
ustomAdapter e
xtends R
ecyclerView .Adapter <CustomAdapter .M
yViewHolder >{
ArrayList
<S
tring >personNames ;
ArrayList
<S
tring >emailIds ;
ArrayList
<S
tring >mobileNumbers ;
Context
context ;
public
CustomAdapter (Context
context ,ArrayList <S
tring >
personNames ,ArrayList
<S
tring
>
emailIds ,A
rrayList <S
tring >mobileNumbers ){
this
.context= context ;
this
.personNames= personNames ;
this
.emailIds=
emailIds ;
this
.mobileNumbers=
mobileNumbers ;
}
@Override
public
MyViewHolder
onCreateViewHolder (ViewGroup parent,int
viewType ){
//
infalte the item Layout
View
v=LayoutInflater .from (p
arent .g
etContext ()).inflate(R
.l
ayout .r
owlayout
,
parent,false);
MyViewHolder
vh=newMyViewHolder (v)
;//
pass theviewtoView Holder
return
vh;
}
@Override
public
void onBindViewHolder (M
yViewHolder
holder ,finali
nt
position ){
//
set the data in items
h
older .name .s
etText (personNames .g
et(position ));
h
older .email .setText (e
mailIds .get(p
osition ));
h
older .mobileNo .s
etText (mobileNumbers .g
et(p
osition ));
//
implement setOnClickListener event onitem view.
h
older .itemView .s
etOnClickListener (newView.O
nClickListener (){
@Override
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
450
public v
oid
onClick (View
view ){
//
display a toast withperson nameonitem click
Toast
.makeText (c
ontext ,personNames .get(position ),
Toast
.LENGTH_SHORT ).
show ();
}
});
}
@Override
public
i
nt
getItemCount (){
return
personNames .s
ize ();
}
public
c
lass M
yViewHolder extends R
ecyclerView .V
iewHolder {
TextView
name,email,mobileNo ;//initthe
item view's
public
M
yViewHolder (View
itemView ){
super (itemView );
//get the reference ofitem view's
n
ame= (
TextView )itemView .findViewById (R.
id
.name);
e
mail= (T
extView )itemView .f
indViewById (R
.i
d.e
mail );
m
obileNo= (T
extView )
itemView .f
indViewById (R.
id
.m
obileNo );
}
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
451
AsyncTask
InAndroid,AsyncTask(AsynchronousTask)allowsustoruntheinstructioninthebackground
andthensynchronizeagainwithourmainthread.Thisclasswilloverrideatleastonemethod
i.edoInBackground(Params)andmostoftenwilloverridesecondmethod
onPostExecute(Result).
AsyncTaskclassisusedtodobackgroundoperationsthatwillupdatetheUI(userinterface).
Mainlyweuseditforshortoperationsthatwillnoteffectonourmainthread.
AsyncTaskclassisfirstlyexecutedusingexecute()method.InthefirststepAsyncTaskiscalled
onPreExecute()thenonPreExecute()callsdoInBackground()forbackgroundprocessesandthen
doInBackground()callsonPostExecute()methodtoupdatetheUI.
NeedofAsyncTaskInAndroid:
Bydefault,ourapplicationcoderunsinourmainthreadandeverystatementistherefore
executeinasequence.Ifweneedtoperformlongtasks/operationsthenourmainthreadis
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
452
blockeduntilthecorrespondingoperationhasfinished.Forprovidingagooduserexperiencein
ourapplicationweneedtouseAsyncTasksclassthatrunsinaseparatethread.Thisclasswill
executeseverythingindoInBackground()methodinsideofotherthreadwhichdoesn’thave
accesstotheGUIwherealltheviewsarepresent.TheonPostExecute()methodofthisclass
synchronizesitselfagainwiththemainUIthreadandallowsittomakesomeupdating.This
methodiscalledautomaticallyafterthedoInBackgroundmethodfinisheditswork.
SyntaxofAsyncTaskInAndroid:
TouseAsyncTaskyoumustsubclassit.TheparametersarethefollowingAsyncTask
<TypeOfVarArgParams,ProgressValue,ResultValue>.Hereisthe
SyntaxofAsyncTaskclass:
privatec
lass D
ownloadFilesTask e
xtendsA
syncTask <U
RL,Integer
,L
ong
>{
protected L
ongdoInBackground(URL
...
urls
){
//
codethat willrun
inthe
background
return
;
}
protected v
oidonProgressUpdate (I
nteger...
progress ){
//
receive progressupdatesfrom doInBackground
}
protected v
oidonPostExecute(L
ong
result
){
//
update theUIafterbackground processes completes
}
}
ExecutionsofAsyncTaskclassfrommainthread:
HereistheSyntaxforexecutionofAsyncTasksclasss.
new
D
ownloadFilesTask
().
execute
(u
rl1
,
url2
,
url3
);
AsyncTask’sgenerictypesInAndroid:
ThethreetypesusedbyAsynchronoustaskarethefollowing
AsyncTask<TypeOfVarArgParams,ProgressValue,ResultValue>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
453
1.TypeOfVarArgParams:P
aramsisthetypeoftheparameterssenttothetaskupon
execution.
2.ProgressValue:Progressisthetypeoftheprogressunitspublishedduringthebackground
computation.
3.ResultValue:ResultValueisthetypeoftheresultofthebackgroundcomputation.
MethodofAsyncTaskInAndroid:
InAndroid,AsyncTaskisexecutedandgoesthroughfourdifferentstepsormethod.Hereare
thesefourmethodsofAsyncTasks.
1.onPreExecute()–ItinvokedonthemainUIthreadbeforethetaskisexecuted.Thismethod
ismainlyusedtosetupthetaskforinstancebyshowingaProgressBarorProgressDialoginthe
UI(userinterface).
2.doInBackground(Params)–Thismethodisinvokedonthebackgroundthreadimmediately
afteronPreExecute()finishesitsexecution.Mainpurposeofthismethodistoperformthe
backgroundoperationsthatcantakealongtime.TheparametersoftheAsynchronoustaskare
passedtothisstepforexecution.Theresultoftheoperationsmustbereturnedbythisstepand
itwillbepassedbacktothelaststep/methodi.eonPostExecutes().Thismethodcanalsouse
publishProgress(Progress…)topublishoneormoreunitsofprogress.Thesevalueswillbe
publishedonthemainUIthreadintheonProgressUpdate(Progress…)method.
3.onProgressUpdate(Progress…)–ThismethodisinvokedonthemainUIthreadafteracall
topublishProgress(Progress…).Timingoftheexecutionisundefined.Thismethodisusedto
displayanyformofprogressintheuserinterfacewhilethebackgroundoperationsare
executing.Wecanalsoupdateourprogressstatusforgooduserexperience.
4.onPostExecute(Result)–ThismethodisinvokedonthemainUIthreadafterthe
backgroundoperationfinishesinthedoInBackgroundmethod.Theresultofthebackground
operationispassedtothisstepasaparameterandthenwecaneasilyupdateourUItoshowthe
results.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
454
RulesofAsyncTask:
Thereareafewthreadingrulesthatmustbefollowedforthisclasstoworkproperly:
1.ThisclassmustbeloadedontheUIthread.ThisisdoneautomaticallyasfromJELLY_BEAN.
2.ThetaskinstancemustbecreatedontheUIthread.
3.execute(Params…)methodthatexecutesit,mustbeinvokedontheUIthread.
4.DonotcallonPreExecute(),onPostExecute(Result),doInBackground(Params…),
onProgressUpdate(Progress…)manually,justexecutestheclassandthenwillcallautomatically
forgooduserexperience.
AsyncTaskExampleInAndroidStudio:
Inthisstepbystepexample,weareusingAsyncTaskclassforperformingnetworkoperations.
HerefirstwearegoingtofetchsomedatafromAPI(Webservice)anddisplayitinourUI.For
thatfirstlywecreateaButtonandonclickofitweareexecutingourAsyncTasksclassthat
fetchesthedatainbackgroundandaftergettingresponsefromAPIinpostExecute()methodwe
aredisplayingthesamedatainourUI.
OurAPIurl:
http://mobileappdatabase.in/demo/smartnews/app_dashboard/jsonUrl/single-article.php?articl
e-id=71
Belowyoucandownloadcode,seefinaloutputandfollowstepbystepexplanationofthe
example:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
455
Step1:CreateanewprojectandnameitAsyncTasksExample.
Step2:Openbuild.gradleandaddPicassolibrarydependency.
applyplugin:'
com.android.application'
android{
c
ompileSdkVersion2 5
b
uildToolsVersion" 25.0.3"
d
efaultConfig{
a
pplicationId" com.abhiandroid.asynctasksexample"
m
inSdkVersion1 5
t
argetSdkVersion2 5
v
ersionCode 1
v
ersionName "1.0"
t
estInstrumentationRunner" android.support.test.runner.AndroidJUnitRunner"
}
b
uildTypes{
r
elease{
m
inifyEnabledf alse
p
roguardFiles getDefaultProguardFile
('
proguard-android.txt'
),
'proguard-rules.pro'
}
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
456
dependencies{
c
ompile
fileTree
(dir
:'
libs'
,
include
:[
'*.jar'
])
a
ndroidTestCompile('
com.android.support.test.espresso:espresso-core:2.2.2' ,{
e
xcludeg
roup
:'com.android.support',m
odule:'support-annotations'
})
c
ompile
'com.android.support:appcompat-v7:25.3.1'
c
ompile
'com.android.support.constraint:constraint-layout:1.0.2'
c
ompile
'com.squareup.picasso:picasso:2.5.2'
t
estCompile'
junit:junit:4.12'
}
Step3:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepfirstlywecreateButtontoperformclickeventandTextView‘sandImageViewto
displaythefetchedAPIdata.
<?
xml
version
="
1.0"
encoding ="
utf-8" ?>
<LinearLayout
xmlns:android ="
http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools"
android:layout_width
="match_parent"
android:layout_height
="
match_parent"
android:orientation
="
vertical"
android:padding
="30dp"
tools:context
="
com.abhiandroid.asynctasksexample.MainActivity" >
<Button
android:id
="
@+id/displayData"
android:layout_width
="200dp"
android:layout_height
="
wrap_content"
android:layout_gravity
="center"
android:layout_marginTop
="20dp"
android:background
="@color/colorPrimary"
android:text
="
Display Data"
android:textColor
="
#fff"
android:textSize
="20sp" /
>
<TextView
android:id
="
@+id/titleTextView"
android:layout_width
="wrap_content"
android:layout_height
="
wrap_content"
android:layout_marginTop
="50dp"
android:text
="
Title: "
android:textColor
="
#000"
android:textSize
="18sp" /
>
<TextView
android:id
="
@+id/categoryTextView"
android:layout_width
="wrap_content"
android:layout_height
="
wrap_content"
android:layout_marginTop
="5dp"
android:text
="
Category: "
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
457
ndroid:textColor
a ="#000"
android:textSize
="
18sp"/
>
<ImageView
android:id
="
@+id/imageView"
android:scaleType
="
centerCrop"
android:layout_width
="match_parent"
android:layout_height
="200dp"
android:layout_gravity
="
center"
android:layout_marginTop
="
20dp" /
>
</LinearLayout>
Step4:Opensrc->package->MainActivity.java
InthisstepfirstlywegetthereferenceofButton,TextView‘sandImageView.Afterthatwe
performsetOnClickListenereventonbuttonandexecuteAsyncTasksclass.InAsyncTasksclass
firstlywedisplayaProgressDialoginonPreExecuteMethodthenweimplementtheAPIin
doInBackgroundmethodandaftergettingresponseinpostExecutemethodwesimplyparsethe
JSONdataanddisplaythetitle,categoryandImageinUI.Inthis,wealsousedPicassoLibrary
tofetchtheimagefromURL.
package
com
.a
bhiandroid .asynctasksexample ;
import
android .a
pp.ProgressDialog ;
import
android .o
s.A
syncTask ;
import
android .o
s.B
undle ;
import
android .s
upport .v
7.a
pp.AppCompatActivity ;
import
android .u
til .L
og;
import
android .v
iew .V
iew ;
import
android .w
idget .Button ;
import
android .w
idget .ImageView ;
import
android .w
idget .TextView ;
import
com.s
quareup .p
icasso .P
icasso ;
import
org.j
son.JSONArray ;
import
org.j
son.JSONException ;
import
org.j
son.JSONObject ;
import
java.i
o
.InputStream ;
import
java.i
o
.InputStreamReader ;
import
java.n
et.H
ttpURLConnection ;
import
java.n
et.U
RL;
public
c
lassM
ainActivity extends AppCompatActivity
{
String
apiUrl=
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
458
"http://mobileappdatabase.in/demo/smartnews/app_dashboard/jsonUrl/single-article.php?article
-id=71";
String
title ,image ,category ;
TextView
titleTextView ,categoryTextView ;
ProgressDialog
progressDialog ;
Button
displayData ;
ImageView
imageView ;
@Override
protected
voidonCreate (Bundle
savedInstanceState ){
super
.onCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .a
ctivity_main );
//
get the reference ofView's
t
itleTextView= (T
extView )findViewById (R.i
d.t
itleTextView );
c
ategoryTextView= (TextView )findViewById (R.
id
.c
ategoryTextView );
d
isplayData =(B
utton )findViewById (R.
id.d
isplayData );
i
mageView= (I
mageView )
findViewById (R
.i
d.imageView );
//
implement setOnClickListener event on displayData button
d
isplayData .setOnClickListener (new V
iew .OnClickListener ()
{
@Override
public v
oid onClick (V
iew
v){
//
create object of MyAsyncTasks class andexecute it
MyAsyncTasks
myAsyncTasks= new M
yAsyncTasks ();
m
yAsyncTasks .execute ();
}
});
}
public
c
lass M
yAsyncTasks extends A
syncTask <String ,S
tring ,String >{
@Override
protected
void
onPreExecute (){
super .onPreExecute ();
//display aprogress dialog for good user experiance
p
rogressDialog= newProgressDialog (MainActivity .t
his);
p
rogressDialog .s
etMessage ("Please Wait" );
p
rogressDialog .s
etCancelable (f
alse );
p
rogressDialog .s
how ();
}
@Override
protected
String
doInBackground (String ... params ){
//implement API in
background and store theresponse incurrent
variable
String
current= "";
try{
U
RL url;
HttpURLConnection
urlConnection= null ;
try
{
u
rl= newURL(apiUrl );
u
rlConnection= (H
ttpURLConnection )url
.openConnection ();
InputStream i
n =
urlConnection .getInputStream ();
InputStreamReader isw= new I
nputStreamReader (in);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
459
int
data=
isw.r
ead();
while(
data!=
-
1)
{
c
urrent+ =
(c
har)data
;
d
ata=
isw.read
();
System
.o
ut.p
rint (c
urrent);
}
//return
the
data
to
onPostExecute
method
return
current
;
}c
atch(Exception
e){
e
.p
rintStackTrace ();
}f
inally {
if(u
rlConnection! =n
ull
){
u
rlConnection .d
isconnect ();
}
}
}catch (
Exception
e){
e
.p
rintStackTrace ();
return
"
Exception: "+
e.g
etMessage
();
}
return current;
}
Override
@
protected
void
onPostExecute
(S
tring
s){
Log
.d
(
"data"
,s.
toString
());
//
dismissthe progressdialog after
receiving
data
from
API
p
rogressDialog .d
ismiss();
try
{
//
JSON
Parsing of
data
JSONArray
jsonArray=n ewJ
SONArray(s
);
SONObject
J
oneObject=
jsonArray .getJSONObject (0
);
//
Pullingitemsfrom the array
t
itle=
oneObject .g
etString ("
title");
c
ategory=
oneObject .getString ("
category" );
i
mage=
oneObject .g
etString ("
image");
//
displaythedatainUI
t
itleTextView.setText("Title: "+
title
);
c
ategoryTextView .s
etText ("
Category: "+
category );
//
Picassolibrary todisplay theimage fromURL
Picasso
.w
ith(g
etApplicationContext ())
.l
oad
(image)
.i
nto
(imageView );
}catch (
JSONException
e){
e
.p
rintStackTrace ();
}
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
460
}
Step5:OpenAndroidManifest.xmlfileandaddInternetPermission.
InthisstepwedefinetheInternetpermission.
<?
xml
version="
1.0"
encoding ="utf-8"
?>
<manifest
x
mlns:android ="
http://schemas.android.com/apk/res/android"
package
="
com.abhiandroid.asynctasksexample" >
<uses-permission
a
ndroid:name ="
android.permission.INTERNET" />
<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
a
ndroid:name ="
.MainActivity" >
<intent-filter>
<action
a
ndroid:name ="android.intent.action.MAIN"/
>
<category
a
ndroid:name ="android.intent.category.LAUNCHER"
/
>
</intent-filter>
</activity>
</application>
</manifest>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
461
SplashScreen
SplashScreenismostcommonlythefirststartupscreenwhichappearswhenAppisopened.In
otherwords,itisasimpleconstantscreenforafixedamountoftimewhichisusedtodisplay
thecompanylogo,name,advertisingcontentetc.
Normallyitshowswhenappisfirsttimelaunchedonandroiddeviceoritmaybesomekindof
processthatisusedtoshowscreentouserjustbeforetheapploadscompletely.
ThistutorialwillhelpyoutolearnHowtocreateSplashscreeninyourAndroidapp.
SplashScreenImplementationMethodInAndroid:
Method1ofimplementingSplashScreen:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
462
Createathreadandsettimetosleepafterthatredirecttomainappscreen.
/******
Create Thread that will sleep for
5seconds****/
T
hread background= new T
hread ()
{
public void
run ()
{
t
ry {
// Thread will sleep for5
seconds
sleep (5
*
1000 );
// After 5seconds redirect toanotherintent
I
ntent
i=n
ewI
ntent (getBaseContext (),
FirstScreen
.c
lass
);
s
tartActivity (i)
;
//Remove activity
finish ();
}catch (
Exception
e){
}
}
};
// start thread
background .start();
Method2ofImplementingSplashScreen:
SettimetohandlerandcallHandler().postDelayed,itwillcallrunmethodofrunnableafterset
timeandredirecttomainappscreen.
HandlersarebasicallybackgroundthreadswhichallowsyoutocommunicatewiththeUIthread
(updatetheUI).
HandlersaresubclassedfromtheAndroidHandlerclassandcanbeusedeitherbyspecifyinga
Runnabletobeexecutedwhenrequiredbythethread,orbyoverridingthehandleMessage()
callbackmethodwithintheHandlersubclasswhichwillbecalledwhenmessagesaresenttothe
handlerbyathread.
TherearetwomainusesforaHandler:
a)ToschedulemessagesandRunnablestobeexecutedatsomepointinthefuture
b)Toenqueueanactiontobeperformedonadifferentthreadthanyourown.
new
H
andler
().
postDelayed
(n
ew
R
unnable
()
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
463
//Using handler with postDelayed calledrunnable
run
method
@Override
p
ublic v
oid
run(){
I
ntent i=
newI
ntent (M
ainSplashScreen .t
his
,F
irstScreen
.c
lass
);
startActivity (i
);
/
/close this activity
finish ();
}
},
5
*1
000 );
/
/ waitfor
5
seconds
SplashScreenImageSizeForDifferentScreenSize:
Androidprovidessupportformultiplescreensizesanddensities,reflectingthemanydifferent
screenconfigurationsthatadevicemayhave.YoucanpreferbelowsizestosupportSplash
Screenondifferentsizesmartphones.
Androiddividestherangeofactualscreensizesanddensitiesinto:
Asetoffourgeneralizedsizes:small,normal,large,andxlarge
Asetofsixgeneralizeddensities:
ldpi(low)~120dpi(240x360px)
mdpi(medium)~160dpi(320x480px)
hdpi(high)~240dpi(480x720px)
xhdpi(extra-high)~320dpi(640x960px)
xxhdpi(extra-extra-high)~480dpi(960x1440px)
xxxhdpi(extra-extra-extra-high)~640dpi(1280x1920px)
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
464
SplashScreenExampleinAndroidStudio
Withthehelpofthistutorialwewillcoverimplementationofsplashscreenintwoscenarios.
FirstwillshowsplashscreenusingHandlerandsecondwewillnotcreatealayoutfileforsplash
screenactivity.Instead,specifyactivity’sthemebackgroundassplashscreenlayout.
InthefirstbelowexamplewewillseetheuseofSplashScreenusingHandlerclass.
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanationofexample:
Step1:C
reateanewprojectandnameitSplashscreen
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepwesimplyaddedacodetodisplaylayoutafterSplashscreen.
<?
xml
version
="
1.0"
encoding
="
utf-8"?>
<RelativeLayoutx
mlns:android="
http://schemas.android.com/apk/res/android"
xmlns:tools
="
http://schemas.android.com/tools"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
465
ndroid:id
a ="
@+id/activity_main"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
tools:context
="
abhiandroid.com.splashscreen.MainActivity" >
<TextView
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:text
="Hello
Worldby
AbhiAndroid!"
android:textSize
="
20sp"
android:layout_centerInParent
="
true"
/>
</RelativeLayout>
Step3:C
reateanewXMLfilesplashfile.xmlforSplashscreenandpastethefollowingcodein
it.
Thislayoutcontainsyourapplogoorotherproductlogothatyouwanttoshowonsplash
screen.
<?
xml
version
="
1.0"
encoding ="
utf-8" ?>
<RelativeLayoutxmlns:android ="http://schemas.android.com/apk/res/android"
android:layout_width ="
match_parent"
android:layout_height ="match_parent"
android:gravity="center"
android:background ="
@color/splashBackground" >
<ImageView
android:id
="
@+id/logo_id"
android:layout_width
="250dp"
android:layout_height
="
250dp"
android:layout_centerInParent
="
true"
android:src
="@drawable/abhiandroid" />
<TextView
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_below
="
@+id/logo_id"
android:layout_centerHorizontal
="
true"
android:text
="
Splash Screen"
android:textSize
="30dp"
android:textColor
="
@color/blue" />
</RelativeLayout>
Step4:N
owopenapp->java->package->MainActivity.javaandaddthebelowcode.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
466
packageabhiandroid .c
om
.splashscreen ;
import
android .s
upport.v
7.a
pp.A
ppCompatActivity ;
import
android .o
s
.B
undle;
publicc
lassM
ainActivity extends A
ppCompatActivity{
@Override
protected
void
onCreate (B
undle savedInstanceState){
super
.onCreate(s
avedInstanceState );
s
etContentView (R
.l
ayout .a
ctivity_main );
}
}
Step5:ForSplashScreenwewillcreateaseparatesplashactivity.Createanewclassinyour
javapackageandnameitasSplashActivity.java.
Step6:AddthiscodeinSplashActivity.javaactivity.Inthiscodehandlerisusedtoholdthe
screenforspecifictimeandoncethehandlerisout,ourmainActivitywillbelaunched.Weare
goingtoholdtheSplashscreenforthreesecond’s.Wewilldefinethesecondsinmillisecond’s
afterPostDelayed(){}method.
1second=1000milliseconds.
PostDelayedmethodwilldelaythetimefor3seconds.Afterthedelaytimeiscomplete,then
yourmainactivitywillbelaunched.
SplashActivity.java
package
abhiandroid.c
om
.s
plashscreen
;
import
android.a
pp
.Activity;
import
android.c
ontent.I
ntent ;
import
android.o
s
.B
undle;
import
android.o
s
.H
andler;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
467
/**
*
Created by AbhiAndroid
*/
public c
lass S
plashActivity e
xtends A
ctivity {
Handler
handler ;
@Override
protected
void
onCreate (B
undle savedInstanceState
){
super
.onCreate(savedInstanceState );
s
etContentView (R.
layout .s
plashfile );
h
andler =n
ew
H
andler ();
h
andler .p
ostDelayed (n
ew R
unnable (){
@Override
public v
oid
run(){
Intent
intent =n
ew I
ntent(S
plashActivity
.t
his
,MainActivity
.c
lass
);
s
tartActivity (i
ntent );
f
inish();
}
},
3000 );
}
}
Step7:OpenAndroidManifest.xmlfileandmakeyoursplashactivity.javaclassasLauncher
activityandmentiontheMainActivityasanotheractivity.
AndroidManifest.xml
<?
xml
version ="
1.0"
encoding ="
utf-8" ?>
<manifestx
mlns:android ="http://schemas.android.com/apk/res/android"
package
="
abhiandroid.com.splashscreen" >
<application
android:allowBackup
="true"
android:icon
="
@drawable/abhiandroid"
android:label
="@string/app_name"
android:supportsRtl
="true"
android:theme
="@style/AppTheme" >
<activity
a
ndroid:name ="
abhiandroid.com.splashscreen.SplashActivity" >
<intent-filter>
<action a
ndroid:name ="
android.intent.action.MAIN"/
>
<category a
ndroid:name ="
android.intent.category.LAUNCHER"/
>
</intent-filter>
</activity>
<activity
a
ndroid:name ="
abhiandroid.com.splashscreen.MainActivity" />
</application>
</manifest>
Output:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
468
NowruntheAppandyouwillseeSplashscreenbeforethemainlayoutloads.
SplashScreenExample2InAndroidStudio:
ThesecondwayislittledifferenttoimplementSplashscreen.Inthisexamplewearegoingto
specifytheSplashscreenbackgroundasanactivity’sthemebackground.
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanationofexample:
Step1:CreateanewprojectandnameitSplashscreen2
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepthecodetodisplaylayoutafterSplashscreenisadded.
<?
xml
version
="
1.0"
encoding
="
utf-8"?>
<RelativeLayoutx
mlns:android="
http://schemas.android.com/apk/res/android"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
469
mlns:tools
x ="http://schemas.android.com/tools"
android:id
="
@+id/activity_main"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:padding
="
20dp"
android:layout_gravity
="center"
tools:context
="
abhiandroid.com.splashscreen2.SecondActivity"
>
<TextView
android:id
="
@+id/hello_id"
android:layout_centerInParent
="
true"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:text
="
Hello
myfriend
"
android:textSize
="
20sp"/>
</RelativeLayout>
Step3:C
reateanewxmllayoutinres⇒drawable⇒splash_screenbackground.xml
InthisexamplewewillnotcreatealayoutfileforSplashscreenactivity.Insteadwewilluse
activitythemebackgroundforSplashscreenlayout.
Here,weusealayerlisttoshowtheimageinthecenterofsplashscreen.Itisnecessarytousea
bitmappedimagetodisplaytheimage.(imageshouldbePNGorJPG)and
splash_background_colorasanbackgroundcolor.
Thefollowingisanexamplecodeofadrawableresourceusinglayer-list.
Addbelowcodeinres⇒drawable.xml⇒
splash_screenbackground.xml
<?
xml
version="1.0"
encoding="
utf-8"?>
<layer-listx
mlns:android ="
http://schemas.android.com/apk/res/android"
>
<item>
<color
a
ndroid:color="@color/splash_background_color"
/>
</item>
<item>
<bitmap
android:src ="
@drawable/mx"
android:tileMode ="disabled"
android:gravity ="
center"/>
</item>
</layer-list>
Step4:Nowopenres⇒values⇒colors.xml
Makesuretoaddbelowcodeincolors.xml
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
470
<?
xml
version="
1.0"
encoding
="
utf-8" ?>
<resources>
<color
n
ame ="
colorPrimary">#3F51B5
</color>
<color
n
ame ="
colorPrimaryDark" >#
303F9F
</color>
<color
n
ame ="
colorAccent">#
FF4081</color>
<color
n
ame ="
splash_background_color" >#
5456e1
</color>
</resources>
Step5:Addthebelowcodeinr es⇒
values⇒styles.xml
Nowwecreateathemeforthesplashscreenactivity.Wecreateacustomthemeforthesplash
screenActivity,andaddtothefilev
alues/styles.xml
res⇒
values⇒styles:
SplashTheme–W
henwedeclarethewindowbackground,itwillremovesthetitlebarfromthe
window,andshowusthefull-screen.ThefileisshownherewithastylenamedSplashTheme.
<resources>
<!--
Baseapplication
theme.-->
<style
n
ame="
AppTheme"
p
arent="
Theme.AppCompat.Light.DarkActionBar" >
<!--
Customize
yourthemehere.-->
<item
n
ame
="
colorPrimary">@color/colorPrimary</item>
<item
n
ame
="
colorPrimaryDark" >@color/colorPrimaryDark</item>
<item
n
ame
="
colorAccent">@
color/colorAccent </item>
</style>
<style
n
ame="
SplashTheme"p
arent=
"Theme.AppCompat.Light.NoActionBar">
<item
n
ame
="
android:windowBackground" >@
drawable/splash_screenbackground
</item>
<item
n
ame
="
android:windowNoTitle" >t
rue
</item>
<item
n
ame
="
android:windowFullscreen" >t
rue
</item>
</style>
</resources>
Step6: AddthebelowcodeinMainActivity.javaandCreateanewSecondActivity.javafor
splashscreen
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
471
Herewewillnotdefinethesetcontentview()fortheSplashscreenactivitybecausewedirectly
applytheSplashThemeonit.NowwejusthavetolaunchtheActivity(SecondActivity)and
thenfinishtheactivitybycallingfinish()method.
MainActivity.java
packageabhiandroid .c
om.splashscreen2 ;
import
android .c
ontent .I
ntent ;
import
android .s
upport .v
7.app
.A
ppCompatActivity ;
import
android .o
s
.Bundle ;
publicc
lassM
ainActivity extends A
ppCompatActivity {
@Override
protected
void
onCreate (B
undle savedInstanceState ){
super
.onCreate (savedInstanceState );
s
tartActivity (n
ewIntent(MainActivity.t
his,S
econdActivity
.c
lass
));
//
closesplash activity
f
inish();
}
}
SecondActivity.java
package abhiandroid .c
om
.s
plashscreen2 ;
import
android .a
pp
.Activity;
import
android .o
s
.B
undle;
/**
*
Created byAbhiAndroid
*/
public c
lassS
econdActivity e
xtends
A
ctivity{
@Override
protected
void
onCreate (B
undle
savedInstanceState
){
super
.onCreate(s
avedInstanceState );
s
etContentView (R
.l
ayout.a
ctivity_main);
}
}
Step7:T
hememustbeassignedtoMainActivityinAndroidManifest
Like–(android:name=”.MainActivity”android:theme=”@style/SplashTheme”>)
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
472
HereisthefullcodeofAndroidManifest:
<?
xml
version="
1.0"
encoding ="utf-8"
?>
<manifest
x
mlns:android ="
http://schemas.android.com/apk/res/android"
package
="
abhiandroid.com.splashscreen2" >
<application
android:allowBackup
="true"
android:icon
="
@mipmap/ic_launcher"
android:label
="@string/app_name"
android:supportsRtl
="true"
android:theme
="@style/AppTheme" >
<activity
a
ndroid:name ="
abhiandroid.com.splashscreen2.MainActivity"
android:theme ="
@style/SplashTheme" >
<intent-filter>
<action
a
ndroid:name ="android.intent.action.MAIN"/
>
<category
a
ndroid:name ="android.intent.category.LAUNCHER"
/
>
</intent-filter>
</activity>
<activity
a
ndroid:name ="
abhiandroid.com.splashscreen2.SecondActivity" />
</application>
</manifest>
Output:
NowruntheAppandyouwillSplashscreenlaunchbeforethemainactivity.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
473
HTMLInAndroid
InAndroid,manytimeswhiledesigninganapplicationwemightbeinasituationwherewe
wouldliketouseHTMLcontentanddisplayinourAppscreen.Itmaybetodisplaysomestatic
contentlikehelp,support,FAQandotherspages.ForthisAndroidprovidesusalovelyclass
android.text.HTMLthatprocessesHTMLstringsintodisplayablestyledtextandthenwecanset
thetextinourTextView.WecanalsouseWebViewfordisplayingHTMLcontent.Currently
AndroiddoesnotsupportalltheHTMLtagsbutitsupportsallmajortags.
HTMLTagsSupportedinAndroidStudio:
AndroidAPIdocumentationdoesnotstipulatewhatHTMLtagsaresupported.Afterlooking
intotheandroidSourcecodeandfromaquicklookatthesourcecode,here’swhatseemstobe
supportedasofnow.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
474
1.b&strongtagforbold
2.i,em,cite&dfntagforItalics
3.utagforUnderline
4.subtagforSubtext
5.suptagforSupertext
6.bigtagforBig
7.smalltagforSmall
8.tttagforMonospace
9.h1toh6tagforHeadlines
10.imgtagforimage
11.fonttagforFontfaceandcolor
12.blockquotetagforlongerquotes
13.atagforLink
14.divandptagforParagraph
15.brtagforLinefeed
HowtoDisplayHTMLinAndroidTextView:
InAndroid,fordisplayingHTMLcontentweuseHTML.fromHtml()method.Thismethodcan
containHtml.ImageGetterasargumentaswellasthetexttoparse.Wecanparsenullasforthe
HTMl.TagHandlerbutweneedtoimplementHTML.ImageGetterasthereisnotanydefault
implementationforthis.TheHtml.ImageGetterneedstorunsynchronouslyandifweare
downloadingimagesfromthewebweprobablywanttodothatasynchronously.Wecanalso
displaytheHTMLcontentinWebViewanditsbetterthendisplayingitinTextView.Inthis
articlewewillshowyoubothexampleswithsameHTMLcontent.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
475
MethodsforParsingHTMLcontentInAndroid:
BelowwedefinesomecommonmethodsusedforparsingHTMLcontent.
1.fromHtml(Stringsource):T
hismethodisusedtodisplaystyledtextfromtheprovided
HTMLstring.ThismethodwasdeprecatedinAPIlevel24.nowpleaseusefromHtml(String,int)
instead.
2.fromHtml(Stringsource,intflags):ThismethodisreplacementoffromHtml(String
source)methodwiththelegacyflagsFROM_HTML_MODE_LEGACY.
3.fromHtml(Stringsource,Html.ImageGetterimageGetter,Html.TagHandler
tagHandler):ThismethodisusedtodisplaystyledtextfromtheprovidedHTMLstring.Any
<img>tagsintheHTMLwillusethespecifiedImageGettertorequestarepresentationofthe
image(usenullifyoudon’twantthis)andthespecifiedTagHandlertohandleunknowntags
(specifynullifyoudon’twantthis).
4.fromHtml(Stringsource,intflags,Html.ImageGetterimageGetter,
Html.TagHandlertagHandler):T hismethodisreplacementoffromHtml(Stringsource,
Html.ImageGetterimageGetter,Html.TagHandlertagHandler)methodwiththelegacyflags
FROM_HTML_MODE_LEGACY.
ConstantFlagsusedwhileParsingHTMLcontent:
BelowwedefinesomecommonflagsthatshouldbeusedinfromHtml()methodforparsing
HTMLcontent.
1.FROM_HTML_MODE_COMPACT:T
hisflagisusedtoseparatetheblocklevelelements
withlinebreakmeanssinglenewlinecharacterinbetween.
2.FROM_HTML_MODE_LEGACY:T
hisflagisusedtoseparatetheblocklevelelementswith
blanklinesmeanstwonewlinecharactersinbetween.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
476
3.FROM_HTML_OPTION_USE_CSS_COLORS:ThisflagisusedtoindicatethatCSScolor
valuesshouldbeusedinsteadofthosedefinedinColor.
4.FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE:Thisflagisusedtoindicate
thattextsinside<blockquote>elementswillbeseparatedfromothertextswithonenewline
characterbydefault.
5.FROM_HTML_SEPARATOR_LINE_BREAK_DIV:Thisflagisusedtoindicatethattexts
inside<div>elementswillbeseparatedfromothertextswithonenewlinecharacterbydefault.
6.FROM_HTML_SEPARATOR_LINE_BREAK_HEADING:Thisflagisusedtoindicatethat
textsinside<h1>,<h2>,<h3>,<h4>,<h5>and<h6>elementswillbeseparatedfromothertexts
withonenewlinecharacterbydefault.
7.FROM_HTML_SEPARATOR_LINE_BREAK_LIST:Thisflagisusedtoindicatethattexts
inside<ul>elementswillbeseparatedfromothertextswithonenewlinecharacterbydefault.
8.FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM:T
hisflagisusedtoindicate
thattextsinside<li>elementswillbeseparatedfromothertextswithonenewlinecharacterby
default.
9.FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH:Thisflagisusedtoindicate
thatinside<p>elementswillbeseparatedfromothertextswithonenewlinecharacterby
default.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
477
Example1OfParseHTMLFilecontentUsingWebViewWithExampleInAndroid
Studio:
BelowistheexampleofHTMLinwhichweparsetheHTMLfileanddisplaytheHTMLcontent
inourAndroidWebView.InthisexamplefirstlywecreateaassetsfolderandstoreaHTMLfile
init.AfterthatwecreateaWebViewinourXMLfileandthengetthereferenceofWebViewin
ourMainActivityandfinallywiththehelpofloadUrl()methodwedisplaythecontentinour
webView.
Step1:C
reateanewprojectandnameitHtmlExample.
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
478
InthisstepweopenanxmlfileandaddthecodefordisplayingaWebView.
<?
xml
version
="
1.0"
encoding="
utf-8"?>
<RelativeLayoutx
mlns: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
="abhiandroid.com.htmlexample.MainActivity" >
<WebView
android:id
="@+id/simpleWebView"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_margin
="20dp"
/
>
</RelativeLayout>
Step3:NowcreateassetsfolderinApp.Youcanreadherehowtocreateassetsfolderin
AndroidStudio
Step4:N
owinsideassetsfolderaddaHTMLfilenamemyfile.html.Youcanreadherehowto
addlocalhtmlfileinAndroidStudio.Alsoinsidemyfile.htmladdthebelowHTMLcontentor
addanycontentinHTMLformat.
<h1>
Heading1<
/h1>
<
h2>
Heading2<
/h2>
<p>
This
is
somehtml. Look,
here's
an<u>
underline
</u>.<
/p>
<p>
Look,
thisis<em>emphasized.
</em>
Andhere\\'ssome<b>
bold
</b>
.</p>
<p>
Here
areUL
list items:
<ul>
<li>
One
</li>
<li>
Two
</li>
<li>
Three</li>
</ul>
<p>
Here
areOL
list items:
<ol>
<li>
One
</li>
<li>
Two
</li>
<li>
Three</li>
</ol>
Step5:N
owOpensrc->package->MainActivity.java
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
479
InthisstepweopenMainActivitywhereweaddthecodetoinitiatetheWebViewandthen
displaytheHTMLcontentfromfilestoredinassetsfolderintoWebView.
packageabhiandroid .c
om.h
tmlexample ;
import
android .o
s.B
undle ;
import
android .s
upport .v7.a
pp.A
ppCompatActivity ;
import
android .w
ebkit .W
ebView ;
publicc
lassMainActivity extends A
ppCompatActivity {
WebView
webView ;
public
S
tring
fileName= "
myfile.html" ;
@Override
protected
v
oidonCreate (B
undle savedInstanceState ){
super
.o
nCreate (savedInstanceState );
s
etContentView (R.l
ayout .activity_main );
//
init webView
w
ebView= (
WebView )findViewById (R
.i
d
.s
impleWebView );
//
displaying content inWebViewfrom htmlfile that
stored
in
assets
folder
w
ebView.getSettings ().
setJavaScriptEnabled (t
rue);
w
ebView.loadUrl ("
file:///android_asset/" +
fileName );
}
}
Output:
NowruntheAppandyouwillseelocalcontentaddedinHTMLfileisloadedinWebview.
Example2OfHTMLInAndroidStudioUsingTextView:
BelowistheexampleofHTMLinwhichwedisplaytheHTMLcontentinourAndroidTextView
withthehelpoffromHtml()method.InthisexamplefirstlywecreateaTextViewinourXML
fileandthengetthereferenceofTextViewinourMainActivityandfinallywiththehelpof
fromHtml()methodwesetthecontentinourTextView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
480
Step1:CreateanewprojectandnameitHtmlExample.
Step2:O
penres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepweopenanxmlfileandaddthecodefordisplayingaTextView.
<?
xml
version
="
1.0"
encoding="
utf-8"?>
<RelativeLayoutx
mlns: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
="
abhiandroid.com.htmlexample.MainActivity" >
<TextView
android:id
="
@+id/simpleTextView"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
481
ndroid:layout_width
a ="wrap_content"
android:layout_height
="wrap_content"
android:layout_margin
="20dp"
/
>
</RelativeLayout>
Step3:N
owOpensrc->package->MainActivity.java
InthisstepweopenMainActivitywhereweaddthecodetoinitiatetheTextViewandthenset
theHTMLcontentwhichisstoredinastringvariableintoTextViewusingfromHtml()method.
packageabhiandroid .c
om.htmlexample ;
import
android .o
s.B
uild ;
import
android .s
upport .v
7.app
.AppCompatActivity ;
import
android .o
s.B
undle ;
import
android .t
ext .H
tml ;
import
android .w
idget .TextView ;
publicc
lass M
ainActivity extends AppCompatActivity {
TextView
textView ;
S
tring
content ="
<h1>Heading 1</h1>\n" +
"
<
h2>Heading 2</h2>\n" +
"
<
p>This is somehtml. Look, here\\'s an<u>underline</u>.</p>\n"
+
"
<
p>Look, this is<em>emphasized.</em> Andhere\\'s
some
<b>bold</b>.</p>\n" +
"
<
p>Here are ULlist items:\n" +
"
<
ul>\n" +
"
<
li>One</li>\n" +
"
<
li>Two</li>\n" +
"
<
li>Three</li>\n" +
"
<
/ul>\n" +
"
<
p>Here are OLlist items:\n" +
"
<
ol>\n" +
"
<
li>One</li>\n" +
"
<
li>Two</li>\n" +
"
<
li>Three</li>\n" +
"
<
/ol>" ;
@Override
protected
v
oidonCreate (B
undle
savedInstanceState ){
super
.o
nCreate (savedInstanceState );
s
etContentView (R.
layout.activity_main );
//
init TextView
t
extView= (T
extView )findViewById (R
.i
d.s
impleTextView );
//
set Textin TextView using fromHtml() method withversioncheck
if
(B
uild .V
ERSION .SDK_INT> =
Build .V
ERSION_CODES .N)
{
t
extView .setText (Html.fromHtml (c
ontent ,H
tml.FROM_HTML_MODE_LEGACY ));
}e
lse
t
extView .setText (Html.fromHtml (c
ontent ));
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
482
}
}
Output:
NowruntheAppandyouwillseeHTMLcontentisshowninTextView.
Example3OfHTMLcontentinWebViewWithExampleinAndroidStudio:
BelowistheexampleofHTMLinwhichwedisplaytheHTMLcontentinourAndroidWebView.
InthisexamplefirstlywecreateaWebViewinourXMLfileandthengetthereferenceof
WebViewinourMainActivityandfinallywiththehelpofloadDataWithBaseURL()methodwe
displaythecontentinourwebView.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
483
Step1:C
reateanewprojectandnameitHtmlWebViewExample.
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
InthisstepweopenanxmlfileandaddthecodefordisplayingaWebView.
<?
xml
version
="
1.0"
encoding="
utf-8"?>
<RelativeLayoutx
mlns: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
="abhiandroid.com.htmlexample.MainActivity" >
<WebView
android:id
="@+id/simpleWebView"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_margin
="20dp"
/
>
</RelativeLayout>
Step3:N
owOpensrc->package->MainActivity.java
InthisstepweopenMainActivitywhereweaddthecodetoinitiatetheWebViewandthen
displaytheHTMLcontentwhichisstoredinastringvariableintoWebView.
packageabhiandroid .c
om.htmlexample ;
import
android .o
s
.B
undle ;
import
android .s
upport .v
7.a
pp
.A
ppCompatActivity ;
import
android .w
ebkit.WebView;
publicc
lassM
ainActivity e
xtendsA
ppCompatActivity {
WebView
webView ;
S
tring
content ="
<h1>Heading 1</h1>\n" +
"
<
h2>Heading 2</h2>\n" +
"
<
p>This is
some html. Look, here\\'s
an<u>underline</u>.</p>\n"
+
"
<
p>Look, thisis <em>emphasized.</em> And
here\\'s
some
<b>bold</b>.</p>\n" +
"
<
p>Here areULlist items:\n" +
"
<
ul>\n"+
"
<
li>One</li>\n" +
"
<
li>Two</li>\n" +
"
<
li>Three</li>\n" +
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
484
"
<
/ul>\n"+
"
<
p>Hereare OL
list items:\n"
+
"
<
ol>\n"+
"
<
li>One</li>\n" +
"
<
li>Two</li>\n" +
"
<
li>Three</li>\n" +
"
<
/ol>"
;
Override
@
protected
v
oidonCreate(B
undle
savedInstanceState ){
super
.o
nCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout
.a
ctivity_main);
//
init
webView
w
ebView=(
W
ebView )
findViewById
(R
.i
d
.s
impleWebView );
//
displaying textin
WebView
w
ebView
.l
oadDataWithBaseURL (n
ull
,content,"
text/html" ,"
utf-8"
,n
ull
);
}
}
Output:
NowruntheAppandyouwillseeHTMLcontentisdisplayedusingWebview.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
485
Fragment
InAndroid,Fragmentisapartofanactivitywhichenablemoremodularactivitydesign.Itwill
notbewrongifwesayafragmentisakindofsub-activity.Itrepresentsabehaviouroraportion
ofuserinterfaceinanActivity.WecancombinemultipleFragmentsinSingleActivitytobuilda
multipanelUIandreuseaFragmentinmultipleActivities.WealwaysneedtoembedFragment
inanactivityandthefragmentlifecycleisdirectlyaffectedbythehostactivity’slifecycle.
ImportantRelatedRead:FragmentLifecycle
WecancreateFragmentsbyextendingFragmentclassorbyinsertingaFragmentintoour
ActivitylayoutbydeclaringtheFragmentintheactivity’slayoutfile,asa<fragment>element.
WecanmanipulateeachFragmentindependently,suchasaddorremovethem.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
486
WhileperformingFragmentTransactionwecanaddaFragmentintobackstackthat’smanaged
bytheActivity.backstackallowustoreverseaFragmenttransactiononpressingBackbuttonof
device.ForExampleifwereplaceaFragmentandadditinbackstackthenonpressingtheBack
buttonondeviceitdisplaythepreviousFragment.
SomeImportantPointsAboutFragmentInAndroid:
1.FragmentswereaddedinHoneycombversionofAndroidi.e APIversion11.
2.Wecanadd,replaceorremoveFragment’sinanActivitywhiletheactivityisrunning.For
performingtheseoperationsweneedaLayout(RelativeLayout,FrameLayoutoranyother
layout)inxmlfileandthenreplacethatlayoutwiththerequiredFragment.
3.Fragmentshasitsownlayoutanditsownbehaviourwithitsownlifecyclecallbacks.
4.Fragmentcanbeusedinmultipleactivities.
5.WecanalsocombinemultipleFragmentsinasingleactivitytobuildamulti-planeUI.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
487
NeedOfFragmentsInAndroid:
BeforetheintroductionofFragment’swecanonlyshowasingleActivityonthescreenatone
givenpointoftimesowewerenotabletodividethescreenandcontroldifferentparts
separately.WiththehelpofFragment’swecandividethescreensindifferentpartsandcontrols
differentpartsseparately.
ByusingFragmentswecancomprisemultipleFragmentsinasingleActivity.Fragmentshave
theirownevents,layoutsandcompletelifecycle.Itprovideflexibilityandalsoremovedthe
limitationofsingleActivityonthescreenatatime..
BasicFragmentCodeInXML:
<fragment
android:id
="
@+id/fragments"
android:layout_width
="match_parent"
android:layout_height
="match_parent"/
>
CreateAFragmentClassInAndroidStudio:
ForcreatingaFragmentfirstlyweextendtheFragmentclass,thenoverridekeylifecycle
methodstoinsertourapplogic,similartothewaywewouldwithanActivityclass.While
creatingaFragmentwemustuseonCreateView()callbacktodefinethelayoutandinorderto
runaFragment.
import
android.o
s.B
undle;
import
android.s
upport .v
4.app.F
ragment ;
import
android.v
iew .L
ayoutInflater ;
import
android.v
iew .V
iewGroup ;
public
c
lass
F
irstFragment e
xtends F
ragment{
@Override
public
V
iew
onCreateView (L
ayoutInflater inflater,ViewGroup
container,
Bundle
savedInstanceState ){
//
Inflate
thelayout for this fragment
return
inflater.inflate(R.
layout .f
ragment_first ,
container,f
alse
);
}
}
HeretheinflaterparameterisaLayoutInflaterusedtoinflatethelayout,containerparameter is
theparentViewGroup(fromtheactivity’slayout)inwhichourFragmentlayoutwillbeinserted.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
488
ThesavedInstanceStateparameterisaBundlethatprovidesdataaboutthepreviousinstanceof
theFragment.Theinflate()methodhasthreeargumentsfirstoneistheresourcelayoutwhich
wewanttoinflate,secondistheViewGrouptobetheparentoftheinflatedlayout.Passingthe
containerisimportantinorderforthesystemtoapplylayoutparameterstotherootviewofthe
inflatedlayout,specifiedbytheparentviewinwhichit’sgoingandthethirdparameterisa
booleanvalueindicatingwhethertheinflatedlayoutshouldbeattachedtotheViewGroup(the
secondparameter)duringinflation.
ImplementationofFragmentInAndroidRequireHoneycomb(3.0)orLater:
FragmentswereaddedininHoneycombversionofAndroidi.e APIversion11.Therearesome
primaryclassesrelatedtoFragment’sare:
1.FragmentActivity:ThebaseclassforallactivitiesusingcompatibilitybasedFragment
(andloader)features.
2.Fragment:T
hebaseclassforallFragmentdefinitions
3.FragmentManager:TheclassforinteractingwithFragmentobjectsinsideanactivity
4.FragmentTransaction:TheclassforperforminganatomicsetofFragmentoperations
suchasReplaceorAddaFragment.
FragmentExample1InAndroidStudio:
BelowistheexampleofFragment’s.InthisexamplewecreatetwoFragmentsandloadthemon
theclickofButton’s.WedisplaytwoButton’sandaFrameLayoutinourActivityandperform
setOnClickListenereventonbothButton’s.OntheclickofFirstButtonwereplacetheFirst
FragmentandonclickofSecondButtonwereplacetheSecondFragmentwiththe
layout(FrameLayout).InthebothFragment’swedisplayaTextViewandaButtonandonclickof
ButtonwedisplaythenameoftheFragmentwiththehelpofToast.
Belowyoucandownloadcode,seefinaloutputandreadstepbystepexplanation:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
489
Step1:C
reateanewprojectandnameitFragmentExample
Step2:Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode
<LinearLayoutx
mlns: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"
android:paddingBottom ="
@dimen/activity_vertical_margin"
android:paddingLeft ="
@dimen/activity_horizontal_margin"
android:paddingRight ="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="
.MainActivity" >
<!--
displaytwo
Button's and aFrameLayout
toreplace
the
Fragment's -
->
<Button
android:id
="
@+id/firstFragment"
android:layout_width ="match_parent"
android:layout_height ="
wrap_content"
android:background="@color/button_background_color"
android:text="
FirstFragment"
android:textColor="@color/white"
android:textSize="
20sp" /
>
<Button
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
490
android:id
="
@+id/secondFragment"
android:layout_width ="
match_parent"
android:layout_height ="wrap_content"
android:layout_marginTop ="10dp"
android:background ="@color/button_background_color"
android:text="Second Fragment"
android:textColor ="@color/white"
android:textSize ="
20sp" /
>
<FrameLayout
android:id
="
@+id/frameLayout"
android:layout_width ="
match_parent"
android:layout_height ="match_parent"
android:layout_marginTop ="10dp" /
>
</LinearLayout>
Step3:Open src->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodeforinitiatetheButton’s.Afterthatwe
performsetOnClickListenereventonbothButton’s.OntheclickofFirstButtonwereplacethe
FirstFragmentandonclickofSecondButtonwereplacetheSecondFragmentwiththe
layout(FrameLayout).ForreplacingaFragmentwithFrameLayoutfirstlywecreateaFragment
ManagerandthenbeginthetransactionusingFragmentTransactionandfinallyreplacethe
Fragmentwiththelayouti.eFrameLayout.
packagecom.a
bhiandroid .fragmentexample ;
import
android .a
pp.Fragment ;
import
android .a
pp.FragmentManager ;
import
android .a
pp.FragmentTransaction ;
import
android .s
upport .v
7.a
pp.AppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .V
iew ;
import
android .w
idget .Button ;
publicc
lass M
ainActivity extends A
ppCompatActivity {
Button
firstFragment ,secondFragment ;
@Override
protected void
onCreate (Bundle savedInstanceState ){
super
.o
nCreate (s
avedInstanceState );
setContentView (R
.l
ayout .activity_main );
//
getthe reference ofButton's
firstFragment= (B
utton )findViewById (R
.i
d.f
irstFragment );
secondFragment= (B
utton )findViewById (R.
id
.secondFragment );
//
perform setOnClickListener event onFirst Button
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
491
firstFragment .s
etOnClickListener (newV
iew.O
nClickListener ()
{
@Override
public
v
oid
onClick (View
v)
{
//
loadFirst Fragment
loadFragment (newF
irstFragment ());
}
});
//
perform setOnClickListener event onSecond Button
secondFragment .s
etOnClickListener (n
ewView
.OnClickListener ()
{
@Override
public
v
oid
onClick (View
v)
{
//
loadSecond Fragment
loadFragment (newS
econdFragment ());
}
});
}
privatev
oid
loadFragment (Fragment fragment ){
//
create a
FragmentManager
FragmentManager
fm=
getFragmentManager ();
//
create a
FragmentTransaction to beginthetransaction andreplace
the
Fragment
FragmentTransaction fragmentTransaction=
fm.b
eginTransaction ();
//
replace the FrameLayout withnew Fragment
fragmentTransaction .replace(R.
id
.f
rameLayout ,
fragment);
fragmentTransaction .commit();//
save thechanges
}
}
Step4:N
owweneed2fragmentsand2xmllayouts.Socreatetwofragmentsbyrightclickon
yourpackagefolderandcreateclassesandnamethemasFirstFragmentandSecondFragment
andaddthefollowingcoderespectively.
FirstFragment.class
InthisFragmentfirstlyweinflatethelayoutandgetthereferenceofButton.Afterthatwe
performsetOnClickListenereventonButtonsowheneverauserclickonthebutton amessage
“FirstFragment“isdisplayedonthescreenbyusing aToast.
package
com
.a
bhiandroid.f
ragmentexample
;
import
android.a
pp
.Fragment;
import
android.o
s
.B
undle;
import
android.v
iew.L
ayoutInflater;
import
android.v
iew.V
iew
;
import
android.v
iew.V
iewGroup ;
import
android.w
idget.B
utton;
import
android.w
idget.T
oast;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
492
public c
lassF
irstFragment extends F
ragment {
View
view;
Button
firstButton ;
@Override
public V
iew
onCreateView (L
ayoutInflater inflater ,ViewGroup
container,
Bundle
savedInstanceState ){
//
Inflate thelayout for this fragment
view=inflater .inflate(R
.l
ayout .f
ragment_first ,
container,false
);
//
get thereference ofButton
firstButton =(B
utton )
view .f
indViewById (R
.i
d.firstButton);
//
perform setOnClickListener onfirstButton
firstButton .setOnClickListener (newV
iew
.OnClickListener ()
{
@Override
public v
oid
onClick (View
v){
//
display a
message byusing aToast
Toast.m
akeText (g
etActivity (), "
First Fragment" ,T
oast.L
ENGTH_LONG).
show();
}
});
return
view
;
}
}
SecondFragment.class
InthisFragmentfirstlyweinflatethelayoutandgetthereferenceofButton.Afterthatwe
performsetOnClickListenereventonButtonsowheneverauserclickonthebutton amessage
“SecondFragment“isdisplayedonthescreenbyusing aToast.
packagecom.a
bhiandroid .f
ragmentexample ;
import
android .a
pp.Fragment ;
import
android .o
s.B
undle ;
import
android .v
iew .L
ayoutInflater ;
import
android .v
iew .V
iew;
import
android .v
iew .V
iewGroup ;
import
android .w
idget .B
utton ;
import
android .w
idget .T
oast ;
publicc
lass S
econdFragment e
xtends F
ragment
{
View
view ;
Button
secondButton ;
@Override
publicV
iew
onCreateView (LayoutInflater
inflater ,V
iewGroup
container,
Bundle
savedInstanceState ){
//
Inflate thelayout forthis fragment
view=
inflater .inflate (R
.l
ayout .f
ragment_second ,container
,false
);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
493
//
getthe
reference of
Button
secondButton= (
Button)
view.findViewById (R.
id
.s
econdButton );
//
performsetOnClickListener on secondButton
secondButton .s
etOnClickListener (n
ewV
iew.O
nClickListener ()
{
@Override
publicv
oid
onClick (V
iewv)
{
//
displayamessage by
using a
Toast
Toast
.m
akeText (g
etActivity (),"
Second Fragment" ,T
oast
.L
ENGTH_LONG
).
show
();
}
});
return
view
;
}
}
Step5: N
owcreate2xmllayoutsbyrightclickingonres/layout->New->LayoutResource
Fileandnamethemasfragment_firstandfragment_secondandaddthefollowingcodein
respectivefiles.
HerewewilldesignthebasicsimpleUIbyusingTextViewandButtoninbothxml’s.
fragment_first.xml
<RelativeLayout x
mlns: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="
com.abhiandroid.fragmentexample.FirstFragment" >
<!--TextViewand Button displayed inFirst
Fragment
-->
<TextView
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_centerHorizontal ="
true"
android:layout_marginTop ="
100dp"
android:text="
This is
First Fragment"
android:textColor ="@color/black"
android:textSize ="25sp" />
<Button
android:id
="
@+id/firstButton"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:layout_centerInParent ="true"
android:layout_marginLeft ="20dp"
android:layout_marginRight ="
20dp"
android:background ="@color/green"
android:text="
First Fragment"
android:textColor ="@color/white"
android:textSize ="20sp"
android:textStyle ="bold" /
>
</RelativeLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
494
Fragment_second.xml:
<RelativeLayout x
mlns: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="
com.abhiandroid.fragmentexample.SecondFragment" >
<!--TextViewand Button displayed inSecond
Fragment
-->
<TextView
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_centerHorizontal ="
true"
android:layout_marginTop ="
100dp"
android:text="
This is
Second Fragment"
android:textColor ="@color/black"
android:textSize ="25sp" />
<Button
android:id
="
@+id/secondButton"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:layout_centerInParent ="
true"
android:layout_marginLeft ="20dp"
android:layout_marginRight ="
20dp"
android:background ="@color/green"
android:text="
Second Fragment"
android:textColor ="@color/white"
android:textSize ="20sp"
android:textStyle ="bold" /
>
</RelativeLayout>
Step6:Openres->values->colors.xml
Inthisstepwedefinethecolor’sthatusedinourxmlfile.
<
?
xmlversion="
1.0"
encoding
="
utf-8"?>
<resources>
<!--
color's used
inour
project-->
<colorn
ame
="
black">#
000</color>
<colorn
ame
="
green">#
0f0</color>
<colorn
ame
="
white">#
fff</color>
<colorn
ame
="
button_background_color" >#
925
</color>
</resources>
Step7:O
penAndroidManifest.xml
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
495
InthisstepweshowtheAndroidManifestfileinwhichdonothingbecausewe needonlyone
Activityi.eMainActivitywhichisalreadydefinedinit.Inourproject wecreatetwoFragment’s
butwedon’tneedtodefinetheFragment’sinmanifestbecauseFragmentisapartofan
Activity.
<?
xml
version ="1.0"
encoding ="
utf-8"?>
<manifest xmlns:android ="http://schemas.android.com/apk/res/android"
package
="com.abhiandroid.fragmentexample" >
<application
android:allowBackup ="true"
android:icon ="@mipmap/ic_launcher"
android:label ="@string/app_name"
android:theme ="@style/AppTheme" >
<activity
android:name =".MainActivity"
android:label ="@string/app_name" >
<intent-filter>
<actiona
ndroid:name ="
android.intent.action.MAIN" /
>
<category android:name ="
android.intent.category.LAUNCHER"/
>
</intent-filter>
</activity>
</application>
</manifest>
Step8:N
owruntheAppandyouwilltwobutton.ClickingonfirstbuttonshowsFirst
FragmentandonclickofSecondButtonshowstheSecondFragmentwhichisactuallyreplacing
layout(FrameLayout).
FragmentExample2InAndroidStudio:
BelowistheexampleofSimpleFragment.InthisexamplewecreateasimpleFragmentand
displayitinourActivitybydeclaringa<fragment>elementinourxmlfile.Wealsodisplaya
Buttoninouractivity’sxmlandperformclickeventsowheneverauserclickonitamessageis
displayedonthescreenbyusingaToast.IntheFragmentwedisplayaTextViewandaButton
andperformclickeventofButtonsowheneverauserclickontheButtonamessageisdisplayed
onthescreenwiththehelpofToast.
Belowyoucandownloadcode,seefinaloutputandreadstepbystepexplanation:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
496
Step1:C
reateanewprojectandnameitFragmentExample
Step2: Openres->layout->activity_main.xml(or)main.xmlandaddfollowingcode:
android
:layout_height ="match_parent"
android
:layout_marginTop ="
10dp" />
<
/LinearLayout><LinearLayout xmlns:android="http:/
/s
chemas.a
ndroid
.c
om
/a
pk
/r
es
/a
ndroid
"
xmlns:tools="http:/
/schemas.android.com/tools"
android
:layout_width ="
match_parent"
android
:layout_height ="match_parent"
android
:orientation="
vertical"
android
:paddingBottom ="@dimen/activity_vertical_margin"
android
:paddingLeft="
@dimen/activity_horizontal_margin"
android
:paddingRight ="
@dimen/activity_horizontal_margin"
android
:paddingTop="
@dimen/activity_vertical_margin"
tools
:c
ontext="
.MainActivity" >
<!--
displayaButtonand
aF
ragment -
->
<
Button
android
:id
="
@+id/activity_button"
android
:layout_width ="
match_parent"
android
:layout_height ="wrap_content"
android
:layout_marginTop ="
10dp"
android
:background="
@color/button_background_color"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
497
android
:t
ext ="
Activity'sButton"
android
:t
extColor ="
@color/white"
android
:t
extSize ="
20sp"
/
>
<
fragment
android
:i
d="
@+id/fragments"
android
:n
ame ="
com.abhiandroid.fragmentexample.SimpleFragment"
android
:l
ayout_width ="
match_parent"
Step3:Open src->package->MainActivity.java
InthisstepweopenMainActivityandaddthecodeforinitiatetheButton.Afterthatwe
performsetOnClickListener onButtonsowheneverauserclickonButtonamessageis
displayedonthescreenwiththehelpofToast.
packagecom.a
bhiandroid .fragmentexample ;
import
android .a
pp.Fragment ;
import
android .a
pp.FragmentManager ;
import
android .a
pp.FragmentTransaction ;
import
android .s
upport .v
7.a
pp.AppCompatActivity ;
import
android .o
s.B
undle ;
import
android .v
iew .V
iew ;
import
android .w
idget .Button ;
import
android .w
idget .Toast ;
publicc
lass M
ainActivity extends A
ppCompatActivity {
Button
activityButton ;
@Override
protected void
onCreate (Bundle savedInstanceState ){
super
.o
nCreate (s
avedInstanceState );
setContentView (R
.l
ayout .activity_main );
//
getthe reference ofButton
activityButton= (B
utton )findViewById (R.
id
.a
ctivity_button );
//
perform setOnClickListener event onButton
activityButton .s
etOnClickListener (n
ew V
iew .O
nClickListener ()
{
@Override
publicv
oid
onClick (V
iew
v){
//
display amessage byusing a
Toast
Toast
.m
akeText (g
etApplicationContext (),"
Activity's Button"
,Toast
.L
ENGTH_LONG
).
show
();
}
});
}
}
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
498
Step4:N
owwecreateafragmentbyrightclickonyourpackagefolderandcreateclassesand
nameitSimpleFragmentandaddthefollowingcode.
InthisFragmentfirstlyweinflatethelayoutandgetthereferenceofButton.Afterthatwe
performsetOnClickListenereventonButtonsowheneverauserclickonthebutton amessage
“Fragment’sButton“isdisplayedonthescreenbyusing aToast.
package com.a
bhiandroid .f
ragmentexample ;
import
android .a
pp.Fragment ;
import
android .o
s.B
undle ;
import
android .v
iew .L
ayoutInflater ;
import
android .v
iew .V
iew;
import
android .v
iew .V
iewGroup ;
import
android .w
idget .Button ;
import
android .w
idget .Toast ;
public c
lass SimpleFragment e
xtends Fragment {
View
view ;
Button
firstButton ;
@Override
public V
iew
onCreateView (LayoutInflater
inflater ,V
iewGroupcontainer,
Bundle
savedInstanceState ){
//
Inflate thelayout forthis fragment
view=inflater .inflate (R
.l
ayout .f
ragment_simple ,container,false
);
//
get the reference of
Button
firstButton =(B
utton )view .f
indViewById (R.
id
.firstButton);
//
perform setOnClickListener on firstButton
firstButton .s
etOnClickListener (newV
iew.O
nClickListener ()
{
@Override
public v
oid
onClick (V
iewv)
{
//
display amessage by
using a
Toast
Toast.m
akeText (g
etActivity (), "
Fragment's Button" ,T
oast
.L
ENGTH_LONG ).show
();
}
});
return
view ;
}
}
Step5:Nowcreateaxmllayoutsbyrightclickingonres/layout->New->LayoutResource
Fileandnamefragment_simpleandaddthefollowingcodeinit.
HerewewilldesignthebasicsimpleUIbyusingTextViewandButton.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
499
<RelativeLayout x
mlns: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="
com.abhiandroid.fragmentexample.SimpleFragment" >
<!--TextViewand Button displayed inSimple
Fragment
-->
<TextView
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:layout_centerHorizontal ="
true"
android:layout_marginTop ="
100dp"
android:text="
Simple Fragment"
android:textColor ="@color/black"
android:textSize ="25sp" />
<Button
android:id
="
@+id/firstButton"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:layout_centerInParent ="true"
android:layout_marginLeft ="20dp"
android:layout_marginRight ="
20dp"
android:background ="@color/green"
android:text="
Fragment's Button"
android:textColor ="@color/white"
android:textSize ="20sp"
android:textStyle ="bold" /
>
</RelativeLayout>
Step6:O
penres->values->colors.xml
Inthisstepwedefinethecolor’sthatusedinourxmlfile.
<?
xml
version ="
1.0"
encoding="
utf-8"?>
<resources>
<!--
color's used
inour
project-->
<colorn
ame
="
black">#
000</color>
<colorn
ame
="
green">#
0f0</color>
<colorn
ame
="
white">#
fff</color>
<colorn
ame
="
button_background_color" >#
925
</color>
</resources>
Step7:O
penAndroidManifest.xml
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
500
InthisstepweshowtheAndroidManifestfileinwhichdonothingbecausewe needonlyone
Activittyi.eMainActivitywhichisalreadydefinedinit.Inourproject weaFragment’sbutwe
don’tneedtodefinetheitinmanifestbecauseFragmentisapartofanActivity.
<?
xml
version ="1.0"
encoding ="
utf-8"?>
<manifest xmlns:android ="http://schemas.android.com/apk/res/android"
package
="com.abhiandroid.fragmentexample" >
<application
android:allowBackup ="true"
android:icon ="@mipmap/ic_launcher"
android:label ="@string/app_name"
android:theme ="@style/AppTheme" >
<activity
android:name =".MainActivity"
android:label ="@string/app_name" >
<intent-filter>
<actiona
ndroid:name ="
android.intent.action.MAIN" /
>
<category android:name ="
android.intent.category.LAUNCHER"/
>
</intent-filter>
</activity>
</application>
</manifest>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
501
BasicCalculatorApp
Doyouusecalculator?OfCourseyoudoinyourregularlife…
SowhynotcreateyourownbasicCalculatorAndroidAppinAndroidStudioanduseitfordoing
thoseoperations.
Ifyoudon’tknowhowtobuiltthenyouarefortreataswearegoingtosharehowtheAppis
createdinAndroid.ThisistheoneofsimplestAppyoucancreatetounderstandAndroid
basics.
InthisCalculatorApptutorialwearegoinguseofmultipleAndroidUIcomponentstodesign
andstepbystepdevelopingaBasicCalculatorapplicationinAndroidStudio.
TopicsUsedForCreatingCalculatorApp–Beforefollowingthebelowstepsitis
recommendedyoucheckoutEditText,TextView,Button&LinearLayouttopics.Alsogo
throughJAVAOOPSconceptonce.
HowToCreateCalculatorAppInAndroidStudio:
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanationofCalculatorApp
inAndroidStudio.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
502
Step1:F irstlygettheandroidstudiodownloadedinyoursystem,thenopenit.
Step2:C
reateanewprojectandnameitCalculator.
Step3:Openres->layout->activity_main.xml(or)main.xml.Herewearegoingtocreatethe
applicationinterfacelikeaddlayouts,Button,TextViewandEditText.
iofStep3–CreateaLinearlayoutvertical,addatextviewfollowedbytwotextfields
Number(decimal)forwritingnumbersinit.Startingcodeofactivity_main.xml
<?
xml
version
="
1.0"
encoding
="
utf-8"
?>
<LinearLayout
xmlns:android="
http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:id
="
@+id/activity_main"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
503
ndroid:layout_width
a ="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="@dimen/activity_vertical_margin"
tools:context
="
abhiandroid.com.calculater.MainActivity"
android:orientation
="vertical"
android:gravity
="
top"
android:textAlignment
="center"
android:background
="@android:color/holo_blue_bright"
android:weightSum
="
1">
<TextView
android:text
="
@string/enter_two_numbers"
android:layout_width
="
match_parent"
android:id
="
@+id/textView"
android:layout_height
="30dp"
android:gravity
="
center_horizontal"
android:textColorLink
="?android:attr/editTextColor"
tools:textStyle
="
bold|italic"
android:textStyle
="
bold|italic"
android:fontFamily
="serif"
android:visibility
="visible"
android:textSize
="24sp"
android:layout_weight
="0.07"
/>
<EditText
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
android:inputType
="
number"
android:ems
="10"
android:id
="
@+id/editOp1"
android:textSize
="18sp"
android:gravity
="
center_horizontal"
android:layout_marginBottom
="
5dp"
android:visibility
="visible" />
<
EditText
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
android:inputType
="
number"
android:ems
="10"
android:id
="
@+id/editOp2"
android:textSize
="18sp"
android:gravity
="
center_horizontal"
android:elevation
="
1dp" />
</LinearLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
504
TheUIwillcurrentlylooklikethis:
iiofStep3–T
henbeforeclosingtheabovelayoutdefineanotherlayoutasLinearlayout
horizontal,addfivebutton(+,-,*,/andClear)definetheirpropertieslikeid,width,heightetc.
initandclosethelinearlayout.
Followingcodeofactivity_main.xml.Thiscodewillbeinsertedinmainlayout:
<LinearLayout
android:orientation
="
horizontal"
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
>
<Button
android:text
="
+"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
505
android:layout_width
="
78dp"
android:layout_height
="wrap_content"
android:id
="
@+id/btnadd"
android:layout_weight
="0.03"/
>
<Button
android:text="
-"
android:layout_width
="
78dp"
android:layout_height
="wrap_content"
android:id
="
@+id/btnsub"
android:layout_weight
="0.03"/
>
<Button
android:text="
*"
android:layout_width
="
78dp"
android:layout_height
="wrap_content"
android:id
="
@+id/btnmul"
android:layout_weight
="0.03"
/>
<Button
android:text="
/"
android:layout_height
="wrap_content"
android:id
="
@+id/btndiv"
android:layout_width
="
78dp"
android:layout_weight
="0.03"/
>
<Button
android:text="
Clear"
android:layout_width="80dp"
android:layout_height ="
wrap_content"
android:id
="
@+id/btnclr"
android:layout_weight ="
0.03"/
>
</LinearLayout>
TheUIwillnowlooklikethis:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
506
iiiofStep3–Furtherincontinuationwithpreviouslinearlayoutaddatextview,
textfield(Number)fordisplayingresultwhichmakestheinterfacecomplete.
Thecompleteinterfacecodeofactivity_main.xml:
<?
xml
version
="
1.0"
encoding ="utf-8" ?>
<LinearLayout
xmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:id
="
@+id/activity_main"
android:layout_width
="match_parent"
android:layout_height
="
match_parent"
android:paddingBottom
="
@dimen/activity_vertical_margin"
android:paddingLeft
="
@dimen/activity_horizontal_margin"
android:paddingRight
="@dimen/activity_horizontal_margin"
android:paddingTop
="@dimen/activity_vertical_margin"
tools:context
="
abhiandroid.com.calculater.MainActivity"
android:orientation
="
vertical"
android:gravity
="top"
android:textAlignment
="
center"
android:background
="@android:color/holo_blue_bright"
android:weightSum
="1"
>
<TextView
android:text
="
@string/enter_two_numbers"
android:layout_width
="
match_parent"
android:id
="
@+id/textView"
android:layout_height
="30dp"
android:gravity
="
center_horizontal"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
507
ndroid:textColorLink
a ="
?android:attr/editTextColor"
tools:textStyle
="
bold|italic"
android:textStyle
="
bold|italic"
android:fontFamily
="serif"
android:visibility
="visible"
android:textSize
="24sp"
android:layout_weight
="
0.07"/
>
<EditText
android:layout_width
="match_parent"
android:layout_height
="
wrap_content"
android:inputType
="number"
android:ems
="10"
android:id
="
@+id/editOp1"
android:textSize
="
18sp"
android:gravity
="center_horizontal"
android:layout_marginBottom
="
5dp"
android:visibility
="visible" />
<
EditText
android:layout_width
="match_parent"
android:layout_height
="
wrap_content"
android:inputType
="number"
android:ems
="10"
android:id
="
@+id/editOp2"
android:textSize
="
18sp"
android:gravity
="center_horizontal"
android:elevation
="1dp"/>
<LinearLayout
android:orientation
="
horizontal"
android:layout_width
="match_parent"
android:layout_height
="
wrap_content" >
<Button
android:text ="
+"
android:layout_width ="
78dp"
android:layout_height ="wrap_content"
android:id ="
@+id/btnadd"
android:layout_weight ="0.03" /
>
<Button
android:text ="
-"
android:layout_width ="
78dp"
android:layout_height ="wrap_content"
android:id ="
@+id/btnsub"
android:layout_weight ="0.03" /
>
<Button
android:text ="
*"
android:layout_width ="
78dp"
android:layout_height ="wrap_content"
android:id ="
@+id/btnmul"
android:layout_weight ="0.03" />
<Button
android:text ="
/"
android:layout_height ="wrap_content"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
508
android:id
="
@+id/btndiv"
android:layout_width
="
78dp"
android:layout_weight
="0.03"/
>
<Button
android:text="
Clear"
android:layout_width="80dp"
android:layout_height ="
wrap_content"
android:id
="
@+id/btnclr"
android:layout_weight ="
0.03"/
>
</LinearLayout>
<TextView
android:text
="
@string/result"
android:layout_width
="
332dp"
android:id
="
@+id/textView1"
android:layout_marginTop
="10dp"
android:layout_height
="50dp"
android:gravity
="
center_horizontal"
android:textColorLink
="?android:attr/editTextColor"
tools:textStyle
="
bold|italic"
android:textStyle
="
bold|italic"
android:fontFamily
="serif"
android:visibility
="visible"
android:textSize
="30sp" /
>
<EditText
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
android:inputType
="
number"
android:ems
="10"
android:id
="
@+id/result"
android:textSize
="18sp"
android:text
="
0.00"
android:gravity
="
center_horizontal" /
>
</LinearLayout>
SonowwehavedesignedthecompleteUIoftheCalculatorApp.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
509
Step4:O
pensrc->package->MainActivity.java.Theinterfacepartoftheapplicationisover,
let’sfocusonaddingfunctionalitytotheapplication.Thiscalculatorappbasicallyperformfive
operationsi.eaddition,subtraction,multiplication,divisionandreset.Soforthatweneedto
definetheseoperationoverbuttonclick.ForthatweusesetOnClickListener()function.
parseDouble()isusedtoconvertStringvaluetodouble.BydefaultthevalueisStringandwe
needtoconvertitintoDoubletoperformoperationoverit.
Ifpersondoesn’tenterthevalueanddirectlyclickontheanybuttonthenaToastmessagewill
appearonthescreentellingusertoentertherequirednumbers.
package
abhiandroid .com.c
alculater ;
import
android .s
upport .v7.a
pp .A
ppCompatActivity ;
import
android .o
s.Bundle ;
import
android .v
iew .View;
import
android .w
idget .B
utton ;
import
android .w
idget .E
ditText ;
import
android .w
idget .T
extView ;
import
android .w
idget .T
oast ;
public
c
lassM
ainActivity extends A
ppCompatActivity {
private
E
ditText
opr1 ;
private
E
ditText
opr2 ;
private
B
utton
btnadd ;
private
Button
btnsub ;
private
Button
btnmul ;
private
B
utton
btndiv ;
private
B
utton
btnclr ;
private
T
extView
txtresult ;
@Override
protected
v
oid
onCreate (Bundle savedInstanceState ){
super
.o
nCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .a
ctivity_main );
o
pr1=(
EditText ) findViewById (R.
id
.editOp1 );
o
pr2=(
EditText ) findViewById (R.
id
.editOp2 );
b
tnadd= (
Button )findViewById (R.
id
.btnadd );
b
tnsub= (
Button )findViewById (R.
id
.btnsub );
b
tnmul= (
Button )findViewById (R.
id
.btnmul );
b
tndiv= (
Button )findViewById (R.
id
.btndiv );
b
tnclr= (
Button )findViewById (R.
id
.btnclr );
t
xtresult =(TextView )findViewById (R.i
d
.result );
/
/
Addition
b
tnadd.s
etOnClickListener (n
ew V
iew .OnClickListener (){
@Override
public v
oid onClick (V
iew v)
{
if
((opr1.getText ().length ()> 0)&
&(
opr2 .g
etText ().
length
()>
0)
)
{
double
oper1= Double .p
arseDouble (opr1
.getText().
toString());
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
510
double
oper2=
Double
.p
arseDouble(o
pr2
.getText
().
toString
());
double
result=
oper1+
oper2
;
t
xtresult
.s
etText(D
ouble.t
oString
(r
esult));
}
else
{
Toast
toast =Toast.makeText (MainActivity .t
his,"
EnterTheRequired
Numbers",Toast .L
ENGTH_LONG );
t
oast .s
how ();
}
}
});
//Subtraction
b
tnsub .s
etOnClickListener (newV
iew .O
nClickListener (){
@Override
public void
onClick (V
iew
v){
if
((opr1.g
etText ().length ()>0)&
&(
opr2
.g
etText ().
length
()>0)
)
{
double oper1= D
ouble .parseDouble (o
pr1
.getText().
toString ());
double oper2= D
ouble .parseDouble (o
pr2
.getText().
toString ());
double result= oper1- oper2;
t
xtresult .s
etText (D
ouble .t
oString (r
esult));
}
else
{
Toast
toast =Toast.makeText (MainActivity .t
his,"
EnterTheRequired
Numbers",Toast .L
ENGTH_LONG );
t
oast .s
how ();
}
}
});
/
/Multiplication
b
tnmul .s
etOnClickListener (newV
iew .O
nClickListener (){
@Override
public void
onClick (V
iew
v){
if
((opr1.g
etText ().length ()>0)&
&(
opr2
.g
etText ().
length
()>0)
)
{
double oper1= D
ouble .parseDouble (o
pr1
.getText().
toString ());
double oper2= D
ouble .parseDouble (o
pr2
.getText().
toString ());
double result= oper1* oper2;
t
xtresult .s
etText (D
ouble .t
oString (r
esult));
}
else
{
Toast
toast =Toast.makeText (MainActivity .t
his,"
EnterTheRequired
Numbers",Toast .L
ENGTH_LONG );
t
oast .s
how ();
}
}
});
/
/Division
b
tndiv .s
etOnClickListener (newV
iew .O
nClickListener (){
@Override
public void
onClick (V
iew
v){
if
((opr1.g
etText ().length ()>0)&
&(
opr2
.g
etText ().
length
()>0)
)
{
double oper1= D
ouble .parseDouble (o
pr1
.getText().
toString ());
double oper2= D
ouble .parseDouble (o
pr2
.getText().
toString ());
double result= oper1/ oper2;
t
xtresult .s
etText (D
ouble .t
oString (r
esult));
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
511
}
else
{
Toast
toast=Toast .makeText(M
ainActivity
.this
,"
Enter
The
Required
Numbers",Toast .L
ENGTH_LONG );
t
oast .s
how();
}
}
});
//
ResetFeilds
b
tnclr .s
etOnClickListener (new
View.OnClickListener
()
{
@Override
public v
oid
onClick (Viewv)
{
o
pr1 .setText(""
);
o
pr2 .setText(""
);
t
xtresult .s
etText ("0.00" );
o
pr1 .requestFocus ();
}
});
}
}
OUTPUT:
NowruntheAppandyouwillseethebasiccalculatorApp.Enteranynumberanddothe
operations.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
512
YoutubeAndroidApp
DoyouknowcreatingYoutubeAndroidAppissoeasyasyoujustneedtounderstandhowto
useYoutubeAPIforthat.
InthisapplicationwewillshareaboutaddingYoutubefunctionalitytoyourAndroid
application.Furtherwewillalsocreateplaylistandrunonrealdevice.Willmakeuseof
multipleAndroidUIcomponentstodesignandstepbystepdevelopingaYoutubeAppin
AndroidStudio.
TopicsUsedForCreatingYoutubeApp–Beforefollowingthebelowstepsitisrecommended
youcheckoutImageView,Button, LinearLayout&RelativeLayouttopics.Alsogothrough
JAVAOOPSconceptonce.
StepsToCreateaYoutubeApplicationInAndroidStudio:
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanationofYoutubeAppin
AndroidStudio.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
513
Step1:F irstlygettheAndroidStudiodownloadedinyoursystem,thenopenit.
Step2:CreateanewprojectchoosebasicactivityandnameitYoutubePlayer.
NowpleasereadthistutorialHowTochoosebasicactivity.
Step3:N
owclickheretodownloadtheYouTubeAndroidPlayerAPI.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
514
Step4:A
fterdownloadingextractthedownloadedcompressedfolder,openitandfinda
executablejarfileinlibsfolder.
Step5:CopythislibraryandpasteinyourYoutubePlayerapplicationa
pp->libs
Step6:Adddependenciestobuild.gradlefileandsync.Addingthiswillmakeourapplication
compatibletoaddyoutubefunctionality.
AddinGradleScripts>>build.gradle(Module:app)
compile
files
('
libs/YouTubeAndroidPlayerApi.jar')
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
515
Step7:Createanewactivity“YoutubeActivity”ofgallerytypeandfurtherselectitasbasic
activity.
Step8:O
penYoutubeActivity.javafile.Hereyouneedtochangethedefaultcode.
iofStep8)FirstlyneedtochangeYoutubeActivityextendsYouTubeBaseActivityimplements
YouTubePlayer.OnInitializedListener.Thiscodewillgiveerror,toremoveitweneedto
implementthecode.
Youcanseeitinbelowscreenshot:
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
516
iiofStep8–GotomenubaronthetopclickCode->Generate->Implementsmethodandclick
ok.Thiswilladdacodewherewecanaddtoastmessagewhenyoutubeinitializationissuccess
andfail.
iiiofStep8)Nextlywegonnaaddlistenersinthecodeas:
youTubePlayer
.s
etPlayerStateChangeListener
(p
layerStateChangeListener
);
y
ouTubePlayer
.s
etPlaybackEventListener
(p
laybackEventListener
);
ivofStep8)Y
ouneedtoaddGoogleAPIKey(it’sauniquekeyusestotakeadvantageof
youtubefunctionality)andYoutubeVideoID(it’stheidofvideowewanttoplay)forthatfollow
followingsteps:
1. Openthislinkfirst.
2. YouneedtologinfirsttogetintothislinkthoughtyourgoogleID.
3. Nowyouneedtocreateaprojectthennamethatproject.
ClickoncredentialsandfurtherclickAPIkey.Therewillbeapop-updisplayingAPIcopyitfor
itsusageintheapplication.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
517
ForVideoIDopenYoutube.comandplayanyvideoyouwishto.TogetthevideoIDcopythe
URLaftertheequaltosign.SimilarlyyoucangetthePlayListIDjustopenrequiredplaylistin
Youtube.
CompleteCODEofYoutubeActivity.java
package
com
.e
xample .y
outubeplayer ;
import
android .o
s
.B
undle ;
import
android .w
idget .T
oast;
import
com.g
oogle.a
ndroid .youtube.p
layer.Y
ouTubeBaseActivity;
import
com.g
oogle.a
ndroid .youtube.p
layer.Y
ouTubeInitializationResult
;
import
com.g
oogle.a
ndroid .youtube.p
layer.Y
ouTubePlayer
;
import
com.g
oogle.a
ndroid .youtube.p
layer.Y
ouTubePlayerView;
public
c
lassY
outubeActivity extends
YouTubeBaseActivity
implements
Y
ouTubePlayer .O
nInitializedListener
{
private
S
tringGOOGLE_API_KEY= "AIzaSyBZVbNSsdQZCX_yWFCHPQ_fQMcK4xf9hDk"
;
private
S
tringYOUTUBE_VIDEO_ID= "
EknEIzswvC0"
;
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
518
Override
@
protected
voidonCreate (B
undle
savedInstanceState ){
super
.onCreate (savedInstanceState );
s
etContentView (R.
layout .activity_youtube );
YouTubePlayerView
youTubePlayerView= (
YouTubePlayerView )
findViewById (R.
i
d.y
outube_player );
y
ouTubePlayerView .i
nitialize (G
OOGLE_API_KEY ,t
his );
}
@Override
public
v
oid onInitializationSuccess (YouTubePlayer .Provider
provider,YouTubePlayer
youTubePlayer ,boolean
wasRestored ){
Toast
.makeText (this ,"Initialized Youtube Player successfully",
Toast
.LENGTH_LONG ).show();
y
ouTubePlayer .s
etPlayerStateChangeListener (playerStateChangeListener );
y
ouTubePlayer .s
etPlaybackEventListener (playbackEventListener );
if
(!
wasRestored ){
y
ouTubePlayer .c
ueVideo (Y
OUTUBE_VIDEO_ID );
}
}
private
Y
ouTubePlayer .PlaybackEventListener
playbackEventListener= n
ew
YouTubePlayer .PlaybackEventListener (){
@Override
public
v
oid
onPlaying (){
Toast .makeText (YoutubeActivity .t
his,"Good, videois
playingok",
Toast
.LENGTH_LONG ).show();
}
@Override
public
v
oid
onPaused (){
Toast .makeText (YoutubeActivity .t
his,"Video haspaused"
,
Toast
.LENGTH_LONG ).show();
}
@Override
public
v
oid
onStopped (){
}
@Override
public
v
oid
onBuffering (boolean b)
{
}
@Override
public
v
oid
onSeekTo (int
i){
}
};
YouTubePlayer
.PlayerStateChangeListener playerStateChangeListener= new
YouTubePlayer .PlayerStateChangeListener (){
@Override
public
v
oid
onLoading (){
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
519
}
Override
@
public
v
oid
onLoaded
(S
tring
s){
}
Override
@
public
v
oid
onAdStarted ()
{
Toast .makeText
(YoutubeActivity .this
,"
ClickAd
now,makethevideo
creator
rich!",T
oast .L
ENGTH_LONG ).
show ();
}
@Override
public
v
oid
onVideoStarted (){
Toast .makeText
(YoutubeActivity .this
,"
Videohasstarted!",
Toast
.LENGTH_LONG ).show
();
}
@Override
public
v
oid
onVideoEnded ()
{
Toast .makeText
(YoutubeActivity .this
,"
Thanksforwatching!",
Toast
.LENGTH_LONG ).show
();
}
@Override
public
v
oid
onError(Y
ouTubePlayer .E
rrorReason
errorReason ){
}
};
@Override
public
v
oid onInitializationFailure (Y
ouTubePlayer.P
rovider
provider,
YouTubeInitializationResult
youTubeInitializationResult ){
Toast
.m
akeText (t
his,"Failed toInitializeYoutube Player"
,
Toast
.LENGTH_LONG ).show
();
}
}
Step9:O
pencontent_youtube.xmlfile,inthisweneedtoextendthelayoutforyoutube
activitybasicallywewilladdacustomviewthatenableustoplayyoutubevideos.
Step10:Firstlychangetherelativelayouttolinearlayoutandadditsorientationtovertical
alsoremovethepaddinginthelayout.Seethecodetobeadded.
Completecodeofcontent_youtube.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"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
520
ndroid:id
a ="
@+id/content_youtube"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
a
ndroid:orientation ="
vertical"
app:layout_behavior
="@string/appbar_scrolling_view_behavior"
tools:context
="com.example.youtubeplayer.YoutubeActivity"
tools:showIn
="
@layout/activity_youtube" >
//customview
to
enable
youtube player
<com.google.android.youtube.player.YouTubePlayerView
android:id
="
@+id/youtube_player"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:background
="
@android:color/white"
>
</com.google.android.youtube.player.YouTubePlayerView>
</LinearLayout>
Step11:AdduserspermissionforinternetinAndroidManifest.xml.
<uses-permission
a
ndroid:name
="android.permission.INTERNET"
/
>
Step12:O
penfilecontent_main.xml,addbuttoninitwhichwillredirectusertoyoutube
player.
<?
xml
version
="
1.0"
encoding ="
utf-8"?>
<RelativeLayout x
mlns: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/content_standalone"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:orientation
="vertical"
app:layout_behavior
="@string/appbar_scrolling_view_behavior"
tools:context
="
com.example.youtubeplayer.MainActivity"
tools:showIn
="@layout/activity_main"
android:background
="@android:color/holo_green_dark" >
<ImageView
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
app:srcCompat
="
@drawable/pic"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
521
ndroid:id
a ="
@+id/imageView"
android:background
="
@android:color/background_dark"
android:layout_alignParentTop
="
true"
/
>
<Button
android:text
="
Next"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_alignTop
="
@+id/btnPlayVideo"
android:layout_centerHorizontal
="true"
android:layout_marginTop
="135dp"
android:textStyle
="
bold|italic"
android:id
="
@+id/next" />
<Button
android:id
="
@+id/btnPlayVideo"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:text
="
@string/play_video"
android:textStyle
="
bold|italic"
android:layout_marginTop
="
93dp"
android:layout_below
="
@+id/imageView"
android:layout_centerHorizontal
="true"/
>
</RelativeLayout>
Step13:N
owopenMainActivity.javaclassandpastethefollowingcode.
InthiscodewegonnaaddtheonclickListeneroverbuttonclicki.eifuserclickonbuttonvideo
willrunandanextbuttonwhichwillredirecttonextactivity.
package
com
.e
xample .y
outubeplayer ;
import
android .c
ontent .Intent ;
import
android .o
s
.B
undle ;
import
android .s
upport .v7.a
pp.AppCompatActivity ;
import
android .s
upport .v7.w
idget .Toolbar;
import
android .v
iew.View;
import
android .w
idget .Button ;
public
c
lassM
ainActivity extends A
ppCompatActivity implements V
iew
.OnClickListener
{
private
B
utton
btnSingle ;
private
Button
btnNext ;
@Override
protected
v
oid
onCreate (B
undle savedInstanceState ){
super
.o
nCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .activity_main );
Toolbar
toolbar= (T
oolbar )
findViewById (R.
id
.t
oolbar );
s
etSupportActionBar (t
oolbar );
b
tnSingle= (B
utton )findViewById (R.
id
.b
tnPlayVideo );
b
tnNext=(
B
utton )findViewById (R
.i
d.n
ext );
b
tnSingle.setOnClickListener (t
his);
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
522
b
tnNext.s
etOnClickListener (this
);
}
@Override
public
v
oid
onClick
(View
v)
{
Intent
intent
=n
ull;
switch
(
v.
getId ()){
caseR.
i
d.b
tnPlayVideo :
i
ntent= n
ewI
ntent
((
MainActivity
.this
),
YoutubeActivity
.c
lass
);
break
;
caseR.
i
d.n
ext:
i
ntent= n
ewI
ntent
((
MainActivity
.this
),
StandaloneActivity
.c
lass
);
break
;
default :
}
if
(i
ntent!=
n
ull
){
s
tartActivity(i
ntent
);
}
}
}
Step14:Similarlycreateanotherbasicactivityandname itStandaloneActivitytoseethe
YoutubePlaylistfunctionality.InthiswewilldefineaPlayListIDthatyoucangetsameaswe
extractedVideoID.
Step15:Opencontent_standalone.xmlfileinthisaddtwobuttonandaddfunctionalityoverit
injavafile.
<?
xmlversion
="
1.0"
encoding ="
utf-8" ?>
<RelativeLayout x
mlns: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/content_standalone"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:orientation
="vertical"
app:layout_behavior
="@string/appbar_scrolling_view_behavior"
tools:context
="
com.example.youtubeplayer.StandaloneActivity"
tools:showIn
="@layout/activity_standalone"
android:background
="@android:color/holo_green_dark" >
<ImageView
android:layout_width
="
match_parent"
android:layout_height
="wrap_content"
app:srcCompat
="
@drawable/pic"
android:id
="
@+id/imageView"
android:background
="@android:color/background_dark"
android:layout_alignParentTop
="true"
android:contentDescription
="@string/pic"/
>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
523
<Button
android:id
="
@+id/btnVideo"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:text
="
@string/play_video"
android:textStyle
="
bold|italic"
android:layout_marginBottom
="
186dp"
android:layout_alignParentBottom
="
true"
android:layout_centerHorizontal
="true"/
>
<Button
android:id
="
@+id/btnPlayList"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:text
="
@string/play_playlist"
android:textStyle
="
bold|italic"
android:layout_marginBottom
="
63dp"
android:layout_above
="
@+id/btnVideo"
android:layout_centerHorizontal
="true"/
>
</RelativeLayout>
Step16:Nowopensrc->package->StandaloneActivity.java.Inthiswegonnaaddthe
onclickListeneroverbuttonclicki.eifuserclickonPlayVideovideowillplayotherwiseon
clickingPlayPlayListplaylistwillrunofdefinedID.
package
com
.e
xample .y
outubeplayer ;
import
android .c
ontent .I
ntent ;
import
android .o
s
.B
undle ;
import
android .s
upport .d
esign .widget .FloatingActionButton ;
import
android .s
upport .d
esign .widget .Snackbar;
import
android .s
upport .v
7.a
pp.A
ppCompatActivity ;
import
android .s
upport .v
7.w
idget .Toolbar ;
import
android .v
iew.V
iew ;
import
android .w
idget .B
utton ;
import
com.g
oogle.a
ndroid .y
outube .p
layer .Y
ouTubeStandalonePlayer ;
public
c
lassS
tandaloneActivity extends A
ppCompatActivity i
mplements
V
iew
.O
nClickListener
{
private
S
tringGOOGLE_API_KEY= "AIzaSyBZVbNSsdQZCX_yWFCHPQ_fQMcK4xf9hDk" ;
private
S
tringYOUTUBE_VIDEO_ID= "
EknEIzswvC0";
private
S
tringYOUTUBE_PLAYLIST_ID ="PLS1QulWo1RIbb1cYyzZpLFCKvdYV_yJ-E" ;
private
B
uttonbtnPlayVideo ;
private
Button
btnPlayplaylist ;
@Override
protected
v
oid
onCreate (B
undle
savedInstanceState ){
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
524
uper
s .o
nCreate
(s
avedInstanceState );
s
etContentView
(R
.l
ayout.a
ctivity_standalone );
T
oolbar
toolbar=
(T
oolbar)
findViewById
(R
.i
d.t
oolbar
);
s
etSupportActionBar (t
oolbar
);
b
tnPlayplaylist =(B
utton
)
findViewById(R.
id
.b
tnPlayList
);
b
tnPlayVideo=(B
utton)
findViewById
(R
.i
d.btnVideo
);
b
tnPlayVideo.s
etOnClickListener (t
his);
btnPlayplaylist .s
etOnClickListener
(this);
}
Override
@
public
v
oid onClick (V
iew
v){
Intent
intent =null ;
switch
(
v.
getId ()){
case R.
i
d.b
tnVideo :
i
ntent=
YouTubeStandalonePlayer .c
reateVideoIntent(t
his
,G
OOGLE_API_KEY,Y
OUTUBE_VIDEO_ID
);
break
;
case R.
i
d.b
tnPlayList :
i
ntent=
YouTubeStandalonePlayer .c
reatePlaylistIntent(t
his
,GOOGLE_API_KEY
,Y
OUTUBE_PLAYLIST_ID
);
break
;
default :
}
if
(i
ntent !=n
ull ){
s
tartActivity (i
ntent );
}
}
}
OUTPUT:
NowruntheAppandusetheplaytheYoutubevideoyouadded.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
525
CountdownTimerAndroid
App
CountDownTimerAppisaboutsettingatimethatmovesinreverselikeitshowsthetimeleft
inupcomingevent.LikewiseherewearemakinganAndroidAppincontexttoCRICKET
WORLDCUPwhichwillstartin2019.Solet’sbeginAppcreationstepbysteptowardsit
completion.
InthisCountDownTimerApptutorialwearegoingtousemultipleAndroidUIcomponentsto
designitsinterfaceinAndroidStudio.
TopicsUsedForCreatingCountDownTimerApp–Beforefollowingthebelowstepsitis
recommendedyoucheckoutTextView,RelativeLayout&LinearLayouttopics.Alsogothrough
JAVAOOPSconceptonce.
HowToCreateCountDownTimerAppInAndroidStudio:
Belowyoucandownloadcode,seefinaloutputandstepbystepexplanationofCountDown
TimerAppinAndroidStudio.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
526
Step1:Firstlygettheandroidstudiodownloadedinyoursystem,thenopenit.
Step2:C
reateanewprojectandnameitCountDownTimer.
Step3:Openres->layout->activity_main.xml(or)main.xml.Herewearegoingtocreatethe
applicationinterfacelikeaddlayouts(linearlayout&relativelayout),TextView.Carefully
analyzethecodeasit’sabitcomplicated,weusedLinearlayoutfordisplayingeachpartof
CountDownTimer(days,hours,minutes,seconds).
Thecompleteinterfacecodeofactivity_main.xml:
<?
xml
version
="
1.0"
encoding ="
utf-8" ?>
<RelativeLayoutxmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
android:id
="
@+id/activity_main"
android:layout_width
="
match_parent"
android:layout_height
="match_parent"
android:paddingBottom
="@dimen/activity_vertical_margin"
android:paddingLeft
="@dimen/activity_horizontal_margin"
android:paddingRight
="
@dimen/activity_horizontal_margin"
android:paddingTop
="
@dimen/activity_vertical_margin"
android:background
="
@drawable/backimage"
tools:context
="
com.example.countdown.MainActivity" >
<TextView
android:layout_width
="wrap_content"
android:layout_height
="
wrap_content"
android:text
="
@string/counter"
android:textSize
="
30sp"
android:textColor
="#ffeeee"
android:textStyle
="bold|italic"
android:layout_above
="@+id/relativeLayout"
android:layout_centerHorizontal
="true"
android:id
="
@+id/textViewheader1" /
>
<RelativeLayout
android:layout_width
="match_parent"
android:layout_height
="
wrap_content"
android:layout_centerVertical
="
true"
android:layout_centerHorizontal
="true"
android:id
="
@+id/relativeLayout" >
<LinearLayout
android:id ="
@+id/LinearLayout"
android:layout_width ="
wrap_content"
android:layout_height ="wrap_content"
android:gravity ="
center"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
527
android:orientation
="
horizontal"
>
<TextView
android:id
="
@+id/tveventStart"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:paddingLeft
="50sp"
android:gravity
="
center"
android:singleLine
="true"
android:text
="
@string/worldcup_2k19"
android:textColor
="
#fff"
android:textSize
="24sp"
android:textStyle
="
bold"
android:visibility
="gone" /
>
<LinearLayout
android:id
="
@+id/LinearLayout1"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_weight
="1"
android:background
="@drawable/counter"
android:gravity
="
center"
android:orientation
="vertical" >
<TextView
android:id
="
@+id/txtDay"
android:layout_width="
fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:gravity
="
center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="
#4a0000"
android:textSize
="35sp"
android:textStyle="
bold" /
>
<TextView
android:id
="
@+id/txt_Day"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:layout_weight ="1"
android:gravity="
center_horizontal"
android:text="
@string/days"
android:textAppearance ="?android:attr/textAppearanceSmall"
android:textColor ="
#fff"
android:textStyle ="
bold"/
>
</LinearLayout>
<LinearLayout
android:id
="
@+id/LinearLayout2"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_weight
="1"
android:background
="
@drawable/counter"
android:gravity
="
center"
android:orientation
="vertical">
<TextView
android:id
="
@+id/txtHour"
android:layout_width
="
fill_parent"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
528
android:layout_height="
wrap_content"
android:layout_weight="
3"
android:gravity
="
center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="
#4a0000"
android:textSize
="35sp"
android:textStyle="
bold"/
>
<TextView
android:id
="
@+id/txt_Hour"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:layout_weight ="1"
android:gravity="
center_horizontal"
android:text="
@string/hours"
android:textAppearance ="?android:attr/textAppearanceSmall"
android:textColor ="
#fff"
android:textStyle ="
bold"/
>
</LinearLayout>
<LinearLayout
android:id
="
@+id/LinearLayout3"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_weight
="1"
android:background
="
@drawable/counter"
android:gravity
="
center"
android:orientation
="vertical">
<TextView
android:id
="
@+id/txtMinute"
android:layout_width="
fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:gravity
="
center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="
#4a0000"
android:textSize
="35sp"
android:textStyle="
bold" /
>
<TextView
android:id
="
@+id/txt_Minute"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:layout_weight ="1"
android:gravity="
center_horizontal"
android:text="
@string/minutes"
android:textAppearance ="?android:attr/textAppearanceSmall"
android:textColor ="
#fff"
android:textStyle ="
bold"/
>
</LinearLayout>
<LinearLayout
android:id
="
@+id/LinearLayout4"
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:layout_weight
="1"
android:background
="
@drawable/counter"
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
529
ndroid:gravity
a ="
center"
android:orientation
="
vertical"
>
<TextView
android:id
="
@+id/txtSecond"
android:layout_width="
fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:gravity
="
center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="
#4a0000"
android:textSize
="35sp"
android:textStyle="
bold" /
>
<TextView
android:id
="
@+id/txt_Second"
android:layout_width ="
fill_parent"
android:layout_height ="wrap_content"
android:layout_weight ="1"
android:gravity="
center_horizontal"
android:text="
@string/seconds"
android:textAppearance ="?android:attr/textAppearanceSmall"
android:textColor ="
#fff"
android:textStyle ="
bold"/
>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
<TextView
android:layout_width
="
wrap_content"
android:layout_height
="wrap_content"
android:text
="
@string/countleft"
android:layout_below
="
@+id/relativeLayout"
android:layout_centerHorizontal
="true"
android:id
="
@+id/textViewheader2"
android:textSize
="
35sp"
android:textStyle
="bold|italic"
android:textColor
="@android:color/background_dark"
/
>
</RelativeLayout>
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
530
Step4:Opensrc->package->MainActivity.java.Theinterfacepartoftheapplicationisover,
let’sfocusonaddingfunctionalitytotheapplication.
InthisappweuseSystemdateandtheupcomingeventdateinourcaseit’s
30-may-2019(WorldCup2k19).Nextlywewillsubtracttheboth datesandgetthetimein
millisecondsfurtherwehavesomearithmeticoperationsoverittogetthelefttimetillthe
eventarrival.
Youalsoseethatweusehandlerinthiscodetoschedulemessageandrunnableinfutureat
somepointandschedulingisaccomplishedbyvariousmethodsbutweused
postDelayed(runnable,long).
packagecom
.e
xample .c
ountdown ;
import
android .s
upport .v7.a
pp.AppCompatActivity ;
import
android .o
s.Bundle ;
import
java.t
ext .S
impleDateFormat ;
import
java.u
til .D
ate ;
import
android .o
s.Handler ;
import
android .v
iew .View ;
import
android .w
idget .TextView ;
publicc
lassMainActivity extends A
ppCompatActivity {
private
T
extView txtDay ,txtHour ,
txtMinute , txtSecond ;
private
T
extView tvEventStart ;
private
H
andler
handler ;
private
R
unnable runnable ;
@Override
protected
v
oid
onCreate (B
undle savedInstanceState ){
super
.o
nCreate (s
avedInstanceState );
s
etContentView (R
.l
ayout .activity_main );
t
xtDay= (
TextView )findViewById (R
.i
d.txtDay );
t
xtHour= (T
extView )findViewById (R
.i
d.txtHour );
t
xtMinute= (T
extView )findViewById (R.i
d.txtMinute );
t
xtSecond= (T
extView )findViewById (R.i
d.txtSecond );
t
vEventStart= (TextView )findViewById (R.
id
.t
veventStart);
c
ountDownStart ();
}
public
v
oidcountDownStart (){
h
andler= newHandler ();
r
unnable= n
ew R
unnable () {
@Override
public v
oid run(){
h
andler .postDelayed (t
his
,1000 );
try
{
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
531
SimpleDateFormat
dateFormat= new S
impleDateFormat (
"yyyy-MM-dd" );
// Please here setyour event date//YYYY-MM-DD
Date futureDate =dateFormat .parse ("2019-5-30" );
Date currentDate= new Date ();
if(!
currentDate .a
fter (futureDate )) {
long
diff=futureDate .getTime ()
-
currentDate .g
etTime ();
long
days=diff/ (2
4*60
*60*
1000
);
d
iff- =days*(24*60
*60*
1000 );
long
hours=
diff/ (60*
60*
1000 );
d
iff- =hours* (6
0 *
60*
1000 );
long
minutes= diff/ (60*
1000 );
d
iff- =minutes* (60*
1000 );
long
seconds= diff/ 1000 ;
t
xtDay .s
etText ("
" +
String .f
ormat ("%02d",days));
t
xtHour .setText (""+String .format ("
%02d",hours));
t
xtMinute .s
etText ("
"
+S
tring .format ("
%02d" ,minutes ));
t
xtSecond .s
etText ("
"
+S
tring .format ("
%02d" ,seconds ));
}else {
t
vEventStart .s
etVisibility (View .V
ISIBLE );
t
vEventStart .s
etText ("The event started!" );
t
extViewGone ();
}
}c
atch(E
xception
e){
e
.p
rintStackTrace ();
}
}
;
}
h
andler.p
ostDelayed
(r
unnable
,1
*
1
000
);
}
public
v
oid
textViewGone()
{
f
indViewById(R
.i
d
.L
inearLayout1
).
setVisibility
(V
iew
.G
ONE
);
f
indViewById(R
.i
d
.L
inearLayout2
).
setVisibility
(V
iew
.G
ONE
);
f
indViewById(R
.i
d
.L
inearLayout3
).
setVisibility
(V
iew
.G
ONE
);
f
indViewById(R
.i
d
.L
inearLayout4
).
setVisibility
(V
iew
.G
ONE
);
f
indViewById(R
.i
d
.t
extViewheader1
).
setVisibility
(V
iew
.G
ONE
);
f
indViewById(R
.i
d
.t
extViewheader2
).
setVisibility
(V
iew
.G
ONE
);
}
}
OUTPUT:
NowruntheAppandyouwillseetheCountDownfortheevent.
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
532
MasterAndroidApp
DevelopmentCourse
Takeyourandroidskillstothenextlevelbybecomingpartofourvideotraining:
YourBenefitsAfterEnrollingInCourse:
○ LearnandMasterAndroidAppDevelopmentFollowingourStep
byStepVideoTrainingcreatedbyRealExperienceAndroid
Developers
○ InsideYouwillFindAndroidContentProperlyStructured
○ BoostYourConfidenceasAndroidDeveloper
○ BuildyourPortfolioUsingourCodes
○ AddourCertificateofCompletiontoYourResumewhichcanbe
VerifiedOnlineforAuthenticity
○ KeepYourselfUpdatedwithAndroidasWewillContinuallykeep
AddingNewTopics
○ UseEcommerceStoreCodetoCreateEcommerceAppand
UltimateWebViewCodetoConvertWebsiteintoAndroidApp
🔥M
ASTERAndroidDevelopmentNOW!🔥
Note:Wealsooffera7daysmoneybackguaranteewithnoquestionsasked.
Ifyouhaveanyqueryorquestioninmind,pleaseemailtoi nfo@abhiandroid.comandIwillget
backtoyouwithin24hours(mostlyASAP).
©
AbhiAndroid.com
-
Enrol
in
ourM
ASTER
ANDROID
COURSE
HERE
533
Thanks!
Thankyouforreading.Ihopeyoulikeit…
FormoreAndroidtutorialsp
leaselikeourFacebookpageandstayintouchwith
AbhiAndroid.com!