Kotlin x Anko (Part 1)

Hey guys! it’s been a while since I’m writing last stories in Medium 😄 … Today, I will tell you a little bit about one of the most famous helper libraries in Android that also written by JetBrains team. It’s called ANKO stands for “Android-Kotlin” (I think) 😆

So, what is it ? refer to their documentation on GitHub https://github.com/Kotlin/anko

It states that “It makes your code clean and easy to read” … wait, we’re using kotlin to make our code in Android more clean and easy to read, right ? so, if you’re using Anko. That means your code will be more beautiful… hmm, interesting, isn’t it ?

Basically, Anko consist of several parts;

  • a lightweight library full of helpers for intents, dialogs, logging and so on)

Ok, let me define those parts one by one with example 😃 … first, we start with the basic. Basic of Anko are consist with the following parts, like;

  • Intents
  • Dialogs and toasts
  • Logging
  • Resources and dimensions

All of this are written in a Kotlin Extensions. Let see on this following example;

class FirstActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
FirstUI().setContentView(this)
val toolbar = find<Toolbar>(R.id.toolbar_first)
toolbar.title = title
toolbar.navigationIcon = ContextCompat.getDrawable(this, R.drawable.bg_arrow_back)
setSupportActionBar(toolbar)
val button = find<Button>(R.id.btn_next)
button.setOnClickListener { startActivity<SecondActivity>() }
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
onBackPressed()
}
}
return super.onOptionsItemSelected(item)
}
}

Did you find any blocks from those following code, right ? these are one of the basic function that comes from Anko library 😆 … so, what is it ? at the first blocks, we set a content view of android layout using Anko DSL components. what is it looks like ?

class FirstUI : AnkoComponent<FirstActivity> {override fun createView(ui: AnkoContext<FirstActivity>) = with(ui) {
coordinatorLayout {
backgroundColor = ContextCompat.getColor(ctx, R.color.colorPrimary)
relativeLayout {
toolbar {
id = R.id.toolbar_first
backgroundColor = ContextCompat.getColor(ctx, R.color.colorPrimaryDark)
elevation = dip(4).toFloat()
setTitleTextColor(ContextCompat.getColor(ctx, R.color.colorPrimary))
}.lparams {
alignParentTop()
width = matchParent
height = wrapContent
}
textView {
id = R.id.tv_first
text = ctx.resources.getString(R.string.text_first)
textColor = ContextCompat.getColor(ctx, R.color.colorPrimaryDark)
textSize = 16f
gravity = Gravity.CENTER
}.lparams {
below(R.id.toolbar_first)
centerInParent()
width = matchParent
height = wrapContent
}
button {
id = R.id.btn_next
text = ctx.resources.getString(R.string.btn_next)
textColor = ContextCompat.getColor(ctx, R.color.colorPrimaryDark)
textSize = 16f
backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent)
topPadding = dip(16)
bottomPadding = dip(16)
}.lparams {
alignParentBottom()
width = matchParent
height = wrapContent
marginEnd = dip(16)
marginStart = dip(16)
bottomPadding = dip(8)
}
}
}
}
}

Same things while we wrote UI in XML, but if you’re using DSL … your code more readable, right 😃 … we used to initialized our view object by this kind of code;

findViewById(R.id.toolbar_first) as Toolbar

And if you’re using Anko, you can easily declare that like this;

find<Toolbar>(R.id.toolbar_first)

Looks more readable, isn’t it ? what about starting an activity. We used to declare like this;

startActivity(Intent(context, SecondActivity::class.java))

In Anko, we can always declare like this;

startActivity<SecondActivity>()

Let see another basic function from Anko, like how to define a logger… usually we define a logger using right ? and we have to declare the tag using our current class… like the following example

cons val TAG = CallersActivity::class.java.simpleName

Let see what Anko offer to define a logger in your current class…

class CallersActivity : AppCompatActivity(), AnkoLogger

That’s it, you just only have to implements the AnkoLogger … and it will be automagically bind to your class 😆 … also, if you need to define log mode from basic Android log… let say, you need to define an info log. It also easily to write it using this;

info("Permissions are granted!")

or

info { "Permissions are denied!" }

What is different with or without using lambda ? the different is if you’re using lambda… will be calculated only if Log.isLoggable(tag, Log.INFO) is true

What about toast ? We used define a toast like this;

Toast.makeText(context, message, Toast.LENGTH_SHORT).show()

In Anko, you can define like this;

toast(message)

Also you don’t need to define a longer way of Android AlertDialog. In Anko you just need this to show an AlertDialog;

alert(R.string.message_question) {
yesButton { snackbar(rootView, R.string.message_yes) }
noButton { longSnackbar(rootView, R.string.message_no) }
}.show()

That is more simple, readable and AWESOME! … In the next part, I’ll tell you some sort story how to create a SQLite DB using Anko. So, stay tuned guys 😃

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store