writing a simple appevcomp.dcc.ufmg.br/wp-content/uploads/kotlin-firstapp.pdf · android studio -...

Post on 31-May-2020

23 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

WritingaSimpleApp

FernandoM.Q.Pereirafernando@dcc.ufmg.br

Whatdoweneedtowriteanapp?

Whatdoweneedtowriteanapp?

-  IntegratedDevelopmentEnvironment

- AndroidStudio

-  Device- orEmulator

WhichIDEsexistforAndroid?

WhichIDEsexistforAndroid?

-  What'swhatabove?

And,whataretheIDEsbelowthatsupportKotlin?

-  Anyothers?

VisualStudio

UnrealEngine

AndroidStudio

CoronaLabs IntelliJIDEA

ApacheCordova

And,whataretheIDEsbelowthatsupportKotlin?

AndroidStudio

IntelliJIDEA

-  TryKotlin

-  Eclipse

-  Vim

-  SublimeTest

-  Atom

-  ...

AndroidStudio

-  Google,JetBrains-  Kotlin,Java,C++

-  Freeware-  Sourcecode

Google intros Android Studio, an IDE for building appshttps://www.engadget.com/2013/05/15/google-android-studio/ ZachHonig,05.15.13

Google releases Android Studio 1.0, the first stable version of its IDEhttps://venturebeat.com/2014/12/08/google-releases-android-studio-1-0-the-first-stable-version-of-its-ide/ EmilProtalinsk,08.12.14

StartingaProjectonAndroidStudio

StartingaProjectonAndroidStudio

RemembertoenableKotlinsupport!

StartingaProjectonAndroidStudio

WhichAPItochoose?

StartingaProjectonAndroidStudio

StartingaProjectonAndroidStudio

TheStructureofaProject

-  Whatareeachofthesefilesandfolders?

TheActivityCode

-  What'sanActivity?

-  Explainthesyntax"Bundle?",e.g.,thequestionmark.

packagecom.example.fernando.helloworld

importandroid.support.v7.app.AppCompatActivityimportandroid.os.Bundle

classMainActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)}}

TheActivityCode

-  What'stheoverridekeyworddoing?

-  Whydon'twehavesemicolons?

packagecom.example.fernando.helloworld

importandroid.support.v7.app.AppCompatActivityimportandroid.os.Bundle

classMainActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)}}

RunningtheApp

EnablinganAndroidDevicetoRunourApp

1.  Onyourdevice,openSettings>AboutphoneandtapBuildnumberseventimes.

EnablinganAndroidDevicetoRunourApp

1.  Returntothepreviousscreen(Settings).Developeroptionsappearsatthebottomofthelist.TapDeveloperoptions.

2.  EnableUSBDebugging.

RunningtheAppontheDevice

-  Clickrun.

Selectthetargetdeviceyouwant

RunningtheAppontheEmulator

-  EmulatorsimulatesanactualAndroiddevice

-  Incomingcalls-  Incomingtextmessages

- Geolocation- Simulatedifferentnetworkspeeds

- Hardwaresensors:- Rotationandbearing

- AccessGooglePlayStore

AndroidVirtualDevice(AVD)

-  Hardwarecharacteristics-  Softwarecharacteristics-  Privatestorage

ThesameemulatorcanrundifferentAndroidVirtualDevices

LaunchingtheEmulator

-  Viathecommandline

$cd/Users/pronesto/Library/Android/sdk/emulator$emulator-avdNexus_5X_API_28-netdelaynone-netspeedfull

-  Viatheandroidstudio- Run→Runapp

LaunchingtheEmulator

-  Viathecommandline

$cd/Users/pronesto/Library/Android/sdk/emulator$emulator-avdNexus_5X_API_28-netdelaynone-netspeedfull

-  Viatheandroidstudio- Run→Runapp- Selectthevirtualdevice

LaunchingtheEmulator

-  Viatheandroidstudio- Run→Runapp- Selectthevirtualdevice

Andbeaware:startingtheemulatormighttakeforever...

LeavetheEmulatorinStandBy

-  Theemulator'sprocessisindependentfromAndroidStudio

-  YoucanevenstartitwithoutAS

CreatinganewAndroidVirtualDevice

-  Viathecommandline

$cd/Users/pronesto/Library/Android/sdk/tools/bin$avdmanagercreateavd-ntest-k"system-images;android-25;google_apis;x86"

CreatinganewAndroidVirtualDevice

-  Viathecommandline

$cd/Users/pronesto/Library/Android/sdk/tools/bin$avdmanagercreateavd-ntest-k"system-images;android-25;google_apis;x86"

-  Viatheandroidstudio- Tools→AVDManager

CreatinganewAndroidVirtualDevice

-  Viathecommandline

$cd/Users/pronesto/Library/Android/sdk/tools/bin$avdmanagercreateavd-ntest-k"system-images;android-25;google_apis;x86"

-  Viatheandroidstudio- Tools→AVDManager→+CreateVirtualDevice

CreatinganewAndroidVirtualDevice

-  Viathecommandline

$cd/Users/pronesto/Library/Android/sdk/tools/bin$avdmanagercreateavd-ntest-k"system-images;android-25;google_apis;x86"

-  Viatheandroidstudio- Tools→AVDManager→+CreateVirtualDevice

-  Youmustselectanimagetodownload

CreatinganewAndroidVirtualDevice

Anotherthingthatcantakeforever...

DEPARTMENTOFCOMPUTERSCIENCEUNIVERSIDADEFEDERALDEMINASGERAIS

FEDERALUNIVERSITYOFMINASGERAIS,BRAZIL

EDITINGTHEACTIVITY

Whatgoesintoeachfolder?

-  Let'sstarttakingalookintothelayoutfolder.Whatdoyouthinkwewillfindthere?

Thisviewhasfourparts.Whatarethey?

Canyoupicturethislayout?

<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Whatarethesetwoviews?

DesignEditororTextEditor?

-  Bothviewshaveadvantagesanddisadvantages.Canyoulistthem?

Exercise:changethetextview

Whataretheresourcevalues?

-  Whatarecolors,stringsandstyles?

-  Howcanwecreatenewvalues?

Creatingnewstrings

<resources> <string name="app_name">HelloWorld</string> <string name="hello_Text">Hello World!</string> </resources>

activity_main.xml

strings.xml

Whataretheadvantagesofusingresources?

AddinganewComponenttotheView

HowtoDeterminethePositionoftheButton?

-  Forinstance,relativetotheTextView?

HowtoDeterminethePositionoftheButton?

-  Forinstance,relativetotheTextView?

<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:text="Button" app:layout_constraintTop_toBottomOf="@+id/textView" tools:layout_editor_absoluteX="147dp" />

Playingwiththelayout

-  Addasecondbuttontoyourview,andtrytopositionthemusingrelativeconstraitns,liketheblueprintontheright.

PlayingwithAttributes

-  Trytochangetheattributesofbuttons.Addnewresourcestoyourcolorpalette.

<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <color name="buttonBackground">#BBDEFB</color> </resources>

PlayingwithAttributes

-  Trytoarriveatthelayoutontheright§.

§:takenfromhttps://codelabs.developers.google.com/codelabs/build-your-first-android-app-kotlin/index.html#5

DEPARTMENTOFCOMPUTERSCIENCEUNIVERSIDADEFEDERALDEMINASGERAIS

FEDERALUNIVERSITYOFMINASGERAIS,BRAZIL

HANDLINGEVENTS

LinkingJavaandXML

-  WhatisthecallsetContentView(...activity_main)doing?

packagecom.example.fernando.helloworld

importandroid.support.v7.app.AppCompatActivityimportandroid.os.Bundle

classMainActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)}}

Addingasimpleevent

-  Wheneverweclickonthe"TOAST"button,weshalldisplaythe"HellowToast!"message.

-  Howtoconnectbuttonandevent?

funtoastMe(view:View){valmyToast=Toast.makeText(this,"HelloToast!",Toast.LENGTH_SHORT)myToast.show()}

Linkingviewandevent

WecanedittheXMLlayoutdirectly

<Button android:id="@+id/toast_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginLeft="24dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:background="@color/buttonBackground" android:onClick="toastMe" android:text="@string/str_toast" android:textSize="18sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" />

AddingtheEventHandlerProgramatically

classMainActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)valtoastButton=findViewById<Button>(R.id.toast)toastButton.setOnClickListener{toastMe()}}privatefuntoastMe(){valmyToast=Toast.makeText(this,"Hello!",Toast.LENGTH_SHORT)myToast.show()}}

Keepingtrackofstate

-  Wewouldliketoadda"countMe"eventontotheapp.

-  ItincrementsthetextwheneverwetouchCOUNT

-  What'sthestateinthiscase?

-  Howtokeeptrackofit?

Implementingthecounter

funcountMe(view:View){//GetthetextviewvalshowCountTextView=findViewById<TextView>(R.id.textView)//Getthevalueofthetextview.valcountString=showCountTextView.text.toString()//Convertvaluetoanumberandincrementitvarcount:Int=Integer.parseInt(countString)count++//Displaythenewvalueinthetextview.showCountTextView.text=count.toString();}

-  Howtoconnectbuttonandevent?

Associatingbuttonwithevent

Creatinganewactivity

-  Again:what'sanactivity?-  WhytohavemultipleactivitiesinanAndroidapp?-  CreateanewemptyactivitycalledSecondActivity.

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.fernando.helloworld"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SecondActivity"></activity> </application> </manifest>

TheManifestFile

-  What'sthemeaningofthedifferententriesforactivities?

-  What'sthedifferencebetweenMAINandLAUNCHER?

MAIN+LAUNCHER

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.fernando.helloworld"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SecondActivity"></activity> </application> </manifest>

TheCodeoftheSecondActivity

-  Let'screatethelayoutforthisactivity.

packagecom.example.fernando.helloworld

importandroid.support.v7.app.AppCompatActivityimportandroid.os.Bundle

classSecondActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_second)}}

AddingoneTextViewtothelayout

TrytoaddthefollowingTextViewtotheLayout

-  Howwouldyouinvokethesecondactivity?

InvokingtheSecondActivity

funrandomMe(view:View){//CreateanIntenttostartthesecondactivityvalrandomIntent=Intent(this,SecondActivity::class.java)//Startthenewactivity.startActivity(randomIntent)}

MainActivity.kt

-  AndhowtoassociatethismethodwiththeRANDOMbutton?

Associatingtheobserverwiththehandler

Thusfar,that'sallthatwehave

-  Howtogeneratearandomnumberbetween1andcount?

-  WeneedtotellSecondActivitywhat'sthevalueofcount.

- Howtodoit?

GlobalVariables

classSecondActivity:AppCompatActivity(){//TOTAL_COUNTislikeastaticvariableinjavacompanionobject{constvalTOTAL_COUNT="total_count"}

overridefunonCreate(savedInstanceState:Bundle?){...}}

SecondActivity.kt

-  WestillneedtotellSecondActivitywhat'sthevalueofcount.

- Howtousetheglobalvariabletodoit?

Senddatafromanactivitytoanother

funrandomMe(view:View){//CreateanIntenttostartthesecondactivityvalrandomIntent=Intent(this,SecondActivity::class.java)

//GetthetextviewvalshowCountTextView=findViewById<TextView>(R.id.textView)

//Getthevalueofthetextview.valcountString=showCountTextView.text.toString()

//Convertthecounttoanintvalcount=Integer.parseInt(countString)

//AddthecounttotheextrasfortheIntent.randomIntent.putExtra(SecondActivity.TOTAL_COUNT,count)

//Startthenewactivity.startActivity(randomIntent)}

MainActivity.kt

Gettinginfofromanotheractivity

-  Now,SecondActivityneedstogettheinformationpassedbyMainActivity,anduseitasthelimittotherandomnumberthatitwilldisplay.- Howtodoit?

Displayingtherandomnumber

classSecondActivity:AppCompatActivity(){companionobject{constvalTOTAL_COUNT="total_count"}

overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_second)showRandomNumber()}

funshowRandomNumber(){...}}

SecondActivity.kt

-  WeneedtoimplementshowRandomNumber...

Displayingtherandomnumber

funshowRandomNumber(){//Getthecountfromtheintentextrasvalcount=intent.getIntExtra(TOTAL_COUNT,0)

//Generatetherandomnumbervalrandom=Random()varrandomInt=0

if(count>0){//AddonebecausetheboundisexclusiverandomInt=random.nextInt(count+1)}

//Displaytherandomnumber.findViewById<TextView>(R.id.textview_random).text=Integer.toString(randomInt)

//Substitutethemaxvalueintothestringresource//fortheheading,andupdatetheheadingfindViewById<TextView>(R.id.textview_label).text=getString(R.string.random_heading,count)}

SecondActivity.kt

Whatarethesetwoparameters?

Buildingstrings

<resources>...<stringname="random_heading">Hereisarandomnumberbetween0and%1d.</string></resources>

strings.xml

top related