SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Downloaden Sie, um offline zu lesen
Anko & Karamba
in Kotlin Bapusaheb Patil
Google-certified Android
Developer & OpenClassrooms
Android Mentor
www.bapspatil.com
My sample app for this talk:
Ankara
bit.do/baps-ankara
What is Anko?
What We Know:
Kotlin reduces boilerplate
(lengthy) code in Android
Development, when compared
with Java.
Anko, if used in Kotlin,
reduces boilerplate code
even further.
What We Need To Know:
+ A bunch of other super
useful stuff I’ll be
covering in this talk
4 Parts of Anko
• Anko Commons
• Anko Layouts
• Anko SQLite
• Anko Coroutines
Setting up Anko...
App-level build.gradle file:
kotlin {
experimental {
coroutines “enable”
}
}
dependencies {
implementation “org.jetbrains.anko:anko:0.10.4”
}
Anko Commons
Usage of Intents:
INTENTS WITHOUT ANKO
val intent = Intent(this, SomeActivity::class.java)
intent.putExtra("id", 13)
startActivity(intent)
Anko Commons
Usage of Intents:
INTENTS WITH ANKO
startActivity<SomeActivity>("id" to 13)
Anko Commons
Usage of Intents:
BROWSER INTENT WITHOUT ANKO
val uri =
Uri.parse(“https://www.bapspatil.com”)
val browserIntent = Intent(Intent.ACTION_VIEW,
uri)
startActivity(browserIntent)
Anko Commons
Usage of Intents:
BROWSER INTENT WITH ANKO
browse(“https://www.bapspatil.com”)
Anko Commons
Usage of Intents:
CALL INTENT WITHOUT ANKO
val uri = Uri.parse(“tel:+917788990099”)
val callIntent = Intent(Intent.ACTION_DIAL)
callIntent.data = uri
startActivity(callIntent)
Anko Commons
Usage of Intents:
CALL INTENT WITH ANKO
makeCall(“+917788990099”)
Anko Commons
Usage of Common Android Components:
TOAST WITHOUT ANKO
Toast.makeText(context,
“Hello, people of BlrKotlin!”,
Toast.LENGTH_SHORT)
.show()
Anko Commons
Usage of Common Android Components:
TOAST WITH ANKO
toast(“Hello, people of BlrKotlin!”)
// longToast(“Hello, people of BlrKotlin!”)
Anko Commons
Usage of Common Android Components:
SNACKBAR WITHOUT ANKO
val snackbar = Snackbar.make(view,
“Hello, people of BlrKotlin!”,
Snackbar.LENGTH_SHORT)
.setAction ( “HI!”,
{ v ->
doSomething()
})
snackbar.show()
Anko Commons
Usage of Common Android Components:
SNACKBAR WITH ANKO
snackbar(view, “Hello, people of BlrKotlin!”, “HI!”){
doSomething()
}
Anko Commons
Usage of Common Android Components:
ALERTDIALOG WITHOUT ANKO
var alertDialog = AlertDialog.Builder(this)
.setMessage("Hi, this is a message for the AlertDialog.")
.setTitle("Title of the AlertDialog")
.setPositiveButton("OK", DialogInterface.OnClickListener { dialog,
which ->
doSomethingPositive()
})
.setNegativeButton("Cancel", DialogInterface.OnClickListener {
dialog, which ->
doSomethingNegative()
})
.create()
.show()
Anko Commons
Usage of Common Android Components:
ALERTDIALOG WITH ANKO
alert(“Hi, this is a message for the AlertDialog.”, “Title of
the AlertDialog”) {
yesButton { doSomethingPositive() }
noButton { doSomethingNegative() }
}.show()
Anko Commons
Usage of Logging:
LOGGING WITHOUT ANKO
Log.v(“MainActivity”, “This activity was
created successfully!”)
Anko Commons
Usage of Logging:
LOGGING WITH ANKO
class MainActivity : AppCompatActivity(),
AnkoLogger {
override fun onCreate(savedInstanceState:
Bundle?) {
verbose(“This activity was created
successfully!”)
}
}
Anko
Layouts
But what’s wrong with XML?
• It forces you to write the same code again.
• It is not typesafe.
• It is not null-safe.
• No code reuse.
• XML parsing is too much overhead. Takes too much CPU time,
and hence battery.
But what’s wrong with XML?
Why not create the UI programmatically?
Why not create the UI programmatically?
Because...it looks ugly. Here’s an example:
val activity = this
val layout = LinearLayout(activity)
layout.orientation = LinearLayout.VERTICAL
val nameEditText = EditText(activity)
val button = Button(activity)
button.text = “Hey There!"
button.setOnClickListener {
Toast.makeText(activity, "Hello there, ${nameEditText.text}!",
Toast.LENGTH_SHORT).show()
}
layout.addView(nameEditText)
layout.addView(button)
All that code...
...just for this?
Enter,
Anko Layouts.
Anko Layouts
MainActivity.kt
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
verticalLayout {
val nameEditText = editText()
button(“Hey There!”) {
onClick {
toast(“Hello there, ${nameEditText.text}!”)
}
}
}
}
This makes Virat
happy too.
Let’s take a
closer look at
Anko Layouts...
Attributes in Anko Layouts DSL
verticalLayout {
lparams(width = matchParent, height = matchParent)
textView {
id = R.id.helloTextView
text = “Hello, people of BlrKotlin!”
textSize = 32f
textColor = 0xffffff.opaque
padding = dip(16)
gravity = Gravity.START // gravity in XML
}.lparams(width = wrapContent, height = wrapContent) {
gravity = Gravity.CENTER // layout_gravity in XML
margin = dip(4)
}
}
AnkoComponent<T>
What is it & why use it?
- It’s a separate class where you can write your DSL code for your UI.
- It is reusable.
- It keeps the UI separate from logic.
- You can convert existing XML files to AnkoComponents with the Anko
Support plugin.
- You also get a layout preview if you install the Anko Support plugin.
Keep UI code in a separate file!
AnkoComponent<T>
MainView.kt
class MainView : AnkoComponent<MainActivity> {
override fun createView(ui: AnkoContext<MainActivity>):
View = with(ui) {
verticalLayout {
...
...
...
}
}
}
AnkoComponent<T>
MainActivity.kt
class MainActivity : AppCompatActivity() {
lateinit val textView: TextView
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
MainView().setContentView(this)
textView = find(R.id.helloTextView)
toast(textView.text)
}
}
Still not convinced about Anko
Layouts?
• 1 parent RelativeLayout
▪ 17 ImageViews
▪ 1 SurfaceView
▪ 2 TextViews
▪ 1 View
Just visit the Wiki at https://bit.do/anko-constraint
Anko
Coroutines
•asReference()
•bg()
asReference()
MainActivity.kt
...
val ref: Ref<MainActivity> = this.asReference()
doAsync {
uiThread {
ref().updateUI()
}
}
...
bg()
MainActivity.kt
...
val ref: Ref<MainActivity> = this.asReference()
doAsync {
val someData = bg { getDataThatTakesLongTimeToFetch() }
uiThread {
ref().updateUI(someData.await())
}
}
...
Karamba
A small bunch of useful Kotlin extensions,
very similar to Anko Commons.
https://bit.do/karamba-kotlin
by matteocrippa
How would you convert a View to a
Bitmap?
val returnedBitmap = Bitmap.createBitmap(view.width,
view.height,Bitmap.Config.ARGB_8888)
val canvas = Canvas(returnedBitmap)
val bgDrawable = view.background
if (bgDrawable != null)
bgDrawable.draw(canvas)
else
canvas.drawColor(Color.WHITE)
view.draw(canvas)
return returnedBitmap
How would you convert a View to a
Bitmap?
val returnedBitmap = view.toBitmap()
How would you resize a Bitmap?
val scaleWidth = newWidth.toFloat() / oldWidth
val scaleHeight = newHeight.toFloat() / oldHeight
val matrix = Matrix()
matrix.postScale(scaleWidth, scaleHeight)
val resizedBitmap = Bitmap.createBitmap(
this, 0, 0, oldWidth, oldHeight, matrix, false)
resizedBitmap.recycle()
return resizedBitmap
How would you resize a Bitmap?
val resizedBitmap = oldBitmap.resize(newWidth, newHeight)
There’s a ton of stuff...
API VERSION:
• support(apiVersion)
• supportLollipop()
• supportKitkat()
BITMAP:
• base64()
• resize(width, height)
BOOLEAN:
• toggle()
• random()
DATE:
• convertTo(format)
[Eg:format=“dd-MM-yy”]
• toCalendar()
• isFuture()
• today()
DOUBLE:
• localCurrency(currency)
[Eg:currency=“USD”]
• celsiusToFahrenheit()
INTEGER:
• commaSeparatedId()
• readableDistanceFromMe
ters()
STRING:
• isValidEmail()
• isPhoneNumber()
• plainText()
• toBitmap()
VIEW:
• toBitmap()
+ more extension functions can be found at
https://bit.do/karamba-kotlin
Thank you.
Bapusaheb Patil
Google-certified Android
Developer & OpenClassrooms
Android Mentor
www.bapspatil.com
GitHub | github.com/bapspatil
LinkedIn | linkedin.com/in/bapspatil
Pinterest | pinterest.com/bapspatil
Twitter | twitter.com/baps_patil
(couldn’t get @bapspatil for this one! ☹)
Play Store | bit.do/bapsapps
Watchfaces | bit.do/bapswat

Weitere ähnliche Inhalte

Was ist angesagt?

HotPush with Ionic 2 and CodePush
HotPush with Ionic 2 and CodePushHotPush with Ionic 2 and CodePush
HotPush with Ionic 2 and CodePush
Evan Schultz
 

Was ist angesagt? (20)

Angular elements - embed your angular components EVERYWHERE
Angular elements - embed your angular components EVERYWHEREAngular elements - embed your angular components EVERYWHERE
Angular elements - embed your angular components EVERYWHERE
 
Design Patterns in XCUITest
Design Patterns in XCUITestDesign Patterns in XCUITest
Design Patterns in XCUITest
 
Wuff: Building Eclipse Applications and Plugins with Gradle
Wuff: Building Eclipse Applications and Plugins with GradleWuff: Building Eclipse Applications and Plugins with Gradle
Wuff: Building Eclipse Applications and Plugins with Gradle
 
GDG Kuwait - Modern android development
GDG Kuwait - Modern android developmentGDG Kuwait - Modern android development
GDG Kuwait - Modern android development
 
Android Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondAndroid Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyond
 
Using JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot appsUsing JHipster for generating Angular/Spring Boot apps
Using JHipster for generating Angular/Spring Boot apps
 
Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6Angular 2 Migration - JHipster Meetup 6
Angular 2 Migration - JHipster Meetup 6
 
React For Vikings
React For VikingsReact For Vikings
React For Vikings
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Java Applets
Java AppletsJava Applets
Java Applets
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
HotPush with Ionic 2 and CodePush
HotPush with Ionic 2 and CodePushHotPush with Ionic 2 and CodePush
HotPush with Ionic 2 and CodePush
 
React JS
React JSReact JS
React JS
 
A journey beyond the page object pattern
A journey beyond the page object patternA journey beyond the page object pattern
A journey beyond the page object pattern
 
JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobileJavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
JavaOne Brasil 2016: JavaEE e HTML5: da web/desktop ao mobile
 
Connect.js 2015 - Building Native Mobile Applications with Javascript
Connect.js 2015 - Building Native Mobile Applications with JavascriptConnect.js 2015 - Building Native Mobile Applications with Javascript
Connect.js 2015 - Building Native Mobile Applications with Javascript
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and PuppeteerE2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
 

Ähnlich wie Anko & Karamba in Kotlin by Bapusaheb Patil

High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
Julien Lecomte
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
Carl Lu
 

Ähnlich wie Anko & Karamba in Kotlin by Bapusaheb Patil (20)

20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native
 
Eclipse 2011 Hot Topics
Eclipse 2011 Hot TopicsEclipse 2011 Hot Topics
Eclipse 2011 Hot Topics
 
Angular 2 Crash Course
Angular  2 Crash CourseAngular  2 Crash Course
Angular 2 Crash Course
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Guides To Analyzing WebKit Performance
Guides To Analyzing WebKit PerformanceGuides To Analyzing WebKit Performance
Guides To Analyzing WebKit Performance
 
AOT(Ahead Of Time)
AOT(Ahead Of Time)AOT(Ahead Of Time)
AOT(Ahead Of Time)
 
[143]Inside fuse deview 2016
[143]Inside fuse   deview 2016[143]Inside fuse   deview 2016
[143]Inside fuse deview 2016
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
 
Introduction to Groovy Monkey
Introduction to Groovy MonkeyIntroduction to Groovy Monkey
Introduction to Groovy Monkey
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
Dev Catchup @ARQGroup
Dev Catchup @ARQGroupDev Catchup @ARQGroup
Dev Catchup @ARQGroup
 
Getting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular DeveloperGetting Started with React, When You’re an Angular Developer
Getting Started with React, When You’re an Angular Developer
 
Compose Camp Day 3 PPT.pptx.pdf
Compose Camp Day 3 PPT.pptx.pdfCompose Camp Day 3 PPT.pptx.pdf
Compose Camp Day 3 PPT.pptx.pdf
 
SpringOne Platform recap 정윤진
SpringOne Platform recap 정윤진SpringOne Platform recap 정윤진
SpringOne Platform recap 정윤진
 
Introduction to Honeycomb APIs - Android Developer Lab 2011 Q3
Introduction to Honeycomb APIs - Android Developer Lab 2011 Q3Introduction to Honeycomb APIs - Android Developer Lab 2011 Q3
Introduction to Honeycomb APIs - Android Developer Lab 2011 Q3
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Anko & Karamba in Kotlin by Bapusaheb Patil

  • 1. Anko & Karamba in Kotlin Bapusaheb Patil Google-certified Android Developer & OpenClassrooms Android Mentor www.bapspatil.com
  • 2. My sample app for this talk: Ankara bit.do/baps-ankara
  • 4. What We Know: Kotlin reduces boilerplate (lengthy) code in Android Development, when compared with Java.
  • 5. Anko, if used in Kotlin, reduces boilerplate code even further. What We Need To Know:
  • 6. + A bunch of other super useful stuff I’ll be covering in this talk
  • 7. 4 Parts of Anko • Anko Commons • Anko Layouts • Anko SQLite • Anko Coroutines
  • 8. Setting up Anko... App-level build.gradle file: kotlin { experimental { coroutines “enable” } } dependencies { implementation “org.jetbrains.anko:anko:0.10.4” }
  • 9. Anko Commons Usage of Intents: INTENTS WITHOUT ANKO val intent = Intent(this, SomeActivity::class.java) intent.putExtra("id", 13) startActivity(intent)
  • 10. Anko Commons Usage of Intents: INTENTS WITH ANKO startActivity<SomeActivity>("id" to 13)
  • 11. Anko Commons Usage of Intents: BROWSER INTENT WITHOUT ANKO val uri = Uri.parse(“https://www.bapspatil.com”) val browserIntent = Intent(Intent.ACTION_VIEW, uri) startActivity(browserIntent)
  • 12. Anko Commons Usage of Intents: BROWSER INTENT WITH ANKO browse(“https://www.bapspatil.com”)
  • 13. Anko Commons Usage of Intents: CALL INTENT WITHOUT ANKO val uri = Uri.parse(“tel:+917788990099”) val callIntent = Intent(Intent.ACTION_DIAL) callIntent.data = uri startActivity(callIntent)
  • 14. Anko Commons Usage of Intents: CALL INTENT WITH ANKO makeCall(“+917788990099”)
  • 15. Anko Commons Usage of Common Android Components: TOAST WITHOUT ANKO Toast.makeText(context, “Hello, people of BlrKotlin!”, Toast.LENGTH_SHORT) .show()
  • 16. Anko Commons Usage of Common Android Components: TOAST WITH ANKO toast(“Hello, people of BlrKotlin!”) // longToast(“Hello, people of BlrKotlin!”)
  • 17. Anko Commons Usage of Common Android Components: SNACKBAR WITHOUT ANKO val snackbar = Snackbar.make(view, “Hello, people of BlrKotlin!”, Snackbar.LENGTH_SHORT) .setAction ( “HI!”, { v -> doSomething() }) snackbar.show()
  • 18. Anko Commons Usage of Common Android Components: SNACKBAR WITH ANKO snackbar(view, “Hello, people of BlrKotlin!”, “HI!”){ doSomething() }
  • 19. Anko Commons Usage of Common Android Components: ALERTDIALOG WITHOUT ANKO var alertDialog = AlertDialog.Builder(this) .setMessage("Hi, this is a message for the AlertDialog.") .setTitle("Title of the AlertDialog") .setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which -> doSomethingPositive() }) .setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, which -> doSomethingNegative() }) .create() .show()
  • 20. Anko Commons Usage of Common Android Components: ALERTDIALOG WITH ANKO alert(“Hi, this is a message for the AlertDialog.”, “Title of the AlertDialog”) { yesButton { doSomethingPositive() } noButton { doSomethingNegative() } }.show()
  • 21. Anko Commons Usage of Logging: LOGGING WITHOUT ANKO Log.v(“MainActivity”, “This activity was created successfully!”)
  • 22. Anko Commons Usage of Logging: LOGGING WITH ANKO class MainActivity : AppCompatActivity(), AnkoLogger { override fun onCreate(savedInstanceState: Bundle?) { verbose(“This activity was created successfully!”) } }
  • 24. But what’s wrong with XML? • It forces you to write the same code again. • It is not typesafe. • It is not null-safe. • No code reuse. • XML parsing is too much overhead. Takes too much CPU time, and hence battery.
  • 25. But what’s wrong with XML?
  • 26. Why not create the UI programmatically?
  • 27. Why not create the UI programmatically? Because...it looks ugly. Here’s an example: val activity = this val layout = LinearLayout(activity) layout.orientation = LinearLayout.VERTICAL val nameEditText = EditText(activity) val button = Button(activity) button.text = “Hey There!" button.setOnClickListener { Toast.makeText(activity, "Hello there, ${nameEditText.text}!", Toast.LENGTH_SHORT).show() } layout.addView(nameEditText) layout.addView(button)
  • 30. Anko Layouts MainActivity.kt override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) verticalLayout { val nameEditText = editText() button(“Hey There!”) { onClick { toast(“Hello there, ${nameEditText.text}!”) } } } }
  • 32. Let’s take a closer look at Anko Layouts...
  • 33. Attributes in Anko Layouts DSL verticalLayout { lparams(width = matchParent, height = matchParent) textView { id = R.id.helloTextView text = “Hello, people of BlrKotlin!” textSize = 32f textColor = 0xffffff.opaque padding = dip(16) gravity = Gravity.START // gravity in XML }.lparams(width = wrapContent, height = wrapContent) { gravity = Gravity.CENTER // layout_gravity in XML margin = dip(4) } }
  • 34. AnkoComponent<T> What is it & why use it? - It’s a separate class where you can write your DSL code for your UI. - It is reusable. - It keeps the UI separate from logic. - You can convert existing XML files to AnkoComponents with the Anko Support plugin. - You also get a layout preview if you install the Anko Support plugin.
  • 35. Keep UI code in a separate file!
  • 36. AnkoComponent<T> MainView.kt class MainView : AnkoComponent<MainActivity> { override fun createView(ui: AnkoContext<MainActivity>): View = with(ui) { verticalLayout { ... ... ... } } }
  • 37. AnkoComponent<T> MainActivity.kt class MainActivity : AppCompatActivity() { lateinit val textView: TextView override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) MainView().setContentView(this) textView = find(R.id.helloTextView) toast(textView.text) } }
  • 38. Still not convinced about Anko Layouts? • 1 parent RelativeLayout ▪ 17 ImageViews ▪ 1 SurfaceView ▪ 2 TextViews ▪ 1 View
  • 39. Just visit the Wiki at https://bit.do/anko-constraint
  • 41. asReference() MainActivity.kt ... val ref: Ref<MainActivity> = this.asReference() doAsync { uiThread { ref().updateUI() } } ...
  • 42. bg() MainActivity.kt ... val ref: Ref<MainActivity> = this.asReference() doAsync { val someData = bg { getDataThatTakesLongTimeToFetch() } uiThread { ref().updateUI(someData.await()) } } ...
  • 43. Karamba A small bunch of useful Kotlin extensions, very similar to Anko Commons. https://bit.do/karamba-kotlin by matteocrippa
  • 44. How would you convert a View to a Bitmap? val returnedBitmap = Bitmap.createBitmap(view.width, view.height,Bitmap.Config.ARGB_8888) val canvas = Canvas(returnedBitmap) val bgDrawable = view.background if (bgDrawable != null) bgDrawable.draw(canvas) else canvas.drawColor(Color.WHITE) view.draw(canvas) return returnedBitmap
  • 45. How would you convert a View to a Bitmap? val returnedBitmap = view.toBitmap()
  • 46. How would you resize a Bitmap? val scaleWidth = newWidth.toFloat() / oldWidth val scaleHeight = newHeight.toFloat() / oldHeight val matrix = Matrix() matrix.postScale(scaleWidth, scaleHeight) val resizedBitmap = Bitmap.createBitmap( this, 0, 0, oldWidth, oldHeight, matrix, false) resizedBitmap.recycle() return resizedBitmap
  • 47. How would you resize a Bitmap? val resizedBitmap = oldBitmap.resize(newWidth, newHeight)
  • 48. There’s a ton of stuff... API VERSION: • support(apiVersion) • supportLollipop() • supportKitkat() BITMAP: • base64() • resize(width, height) BOOLEAN: • toggle() • random() DATE: • convertTo(format) [Eg:format=“dd-MM-yy”] • toCalendar() • isFuture() • today() DOUBLE: • localCurrency(currency) [Eg:currency=“USD”] • celsiusToFahrenheit() INTEGER: • commaSeparatedId() • readableDistanceFromMe ters() STRING: • isValidEmail() • isPhoneNumber() • plainText() • toBitmap() VIEW: • toBitmap() + more extension functions can be found at https://bit.do/karamba-kotlin
  • 49.
  • 50. Thank you. Bapusaheb Patil Google-certified Android Developer & OpenClassrooms Android Mentor www.bapspatil.com GitHub | github.com/bapspatil LinkedIn | linkedin.com/in/bapspatil Pinterest | pinterest.com/bapspatil Twitter | twitter.com/baps_patil (couldn’t get @bapspatil for this one! ☹) Play Store | bit.do/bapsapps Watchfaces | bit.do/bapswat