Share
Embed
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
Transcript
50 slides
-
Anko & Karamba in Kotlin Bapusaheb Patil Google-certified Android Developer
& OpenClassrooms Android Mentor www.bapspatil.com -
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: 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: 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 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!”) } } -
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. -
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) -
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}!”) } } } } -
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. -
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 -
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 -
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