Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Anko & Karamba in Kotlin • Bapusaheb Patil • BlrKotlin's 3rd Meetup

Anko & Karamba in Kotlin • Bapusaheb Patil • BlrKotlin's 3rd Meetup

This is the PPT of my Kotlin talk on Anko & Karamba in BlrKotlin's 3rd Meetup.
March 10th, 2018.

Bapusaheb Patil

March 10, 2018
Tweet

More Decks by Bapusaheb Patil

Other Decks in Programming

Transcript

  1. Anko & Karamba in Kotlin Bapusaheb Patil Google-certified Android Developer

    & OpenClassrooms Android Mentor www.bapspatil.com
  2. 4 Parts of Anko • Anko Commons • Anko Layouts

    • Anko SQLite • Anko Coroutines
  3. Setting up Anko... App-level build.gradle file: kotlin { experimental {

    coroutines “enable” } } dependencies { implementation “org.jetbrains.anko:anko:0.10.4” }
  4. Anko Commons Usage of Intents: INTENTS WITHOUT ANKO val intent

    = Intent(this, SomeActivity::class.java) intent.putExtra("id", 13) startActivity(intent)
  5. 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)
  6. 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)
  7. Anko Commons Usage of Common Android Components: TOAST WITHOUT ANKO

    Toast.makeText(context, “Hello, people of BlrKotlin!”, Toast.LENGTH_SHORT) .show()
  8. Anko Commons Usage of Common Android Components: TOAST WITH ANKO

    toast(“Hello, people of BlrKotlin!”) // longToast(“Hello, people of BlrKotlin!”)
  9. 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()
  10. Anko Commons Usage of Common Android Components: SNACKBAR WITH ANKO

    snackbar(view, “Hello, people of BlrKotlin!”, “HI!”){ doSomething() }
  11. 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()
  12. 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()
  13. Anko Commons Usage of Logging: LOGGING WITH ANKO class MainActivity

    : AppCompatActivity(), AnkoLogger { override fun onCreate(savedInstanceState: Bundle?) { verbose(“This activity was created successfully!”) } }
  14. 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.
  15. 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)
  16. 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}!”) } } } }
  17. 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) } }
  18. 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.
  19. AnkoComponent<T> MainView.kt class MainView : AnkoComponent<MainActivity> { override fun createView(ui:

    AnkoContext<MainActivity>): View = with(ui) { verticalLayout { ... ... ... } } }
  20. 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) } }
  21. Still not convinced about Anko Layouts? • 1 parent RelativeLayout

    ▪ 17 ImageViews ▪ 1 SurfaceView ▪ 2 TextViews ▪ 1 View
  22. bg() MainActivity.kt ... val ref: Ref<MainActivity> = this.asReference() doAsync {

    val someData = bg { getDataThatTakesLongTimeToFetch() } uiThread { ref().updateUI(someData.await()) } } ...
  23. Karamba A small bunch of useful Kotlin extensions, very similar

    to Anko Commons. https://bit.do/karamba-kotlin by matteocrippa
  24. 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
  25. How would you convert a View to a Bitmap? val

    returnedBitmap = view.toBitmap()
  26. 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
  27. 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
  28. 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