Kotlin — Anko & the layouts

Alejandro Moya
Codelitt
2 min readMay 14, 2019

--

In the previous post we found some good tools to help reduce code in Android apps. Now we are going to add a twist, we can remove the XML layouts and create a dynamic UI strictly from code, a real power tool from Anko, as this also makes this process really simple and flexible.

This part of the library is really flexible, you can replace or include xml layouts, and by include I mean you can keep your existing layouts and include them in the dynamic code.

A quick example:

verticalLayout {
padding = dip(5) //remember the dip method from commons?
val user = editText {
hint = “User name”
textSize = 14f
}
val password = editText {
hint = “Password”
textSize = 14f
}
button(“Login”) {
backgroundColor = Color.BLUE
onClick {
toast(“logged in with user ${user.text}”)
}
}
}.lparams {
margin = dip(10)
}

This code is self explanatory, you create a vertical layout with two EditText and one Button, the button is blue and the text size for both fields is 14f, when the button is clicked it shows a toast with the text supplied. The vertical layout has a padding of 5dp and a margin of 10dp, you can also set different sizes for vertical and horizontal, also the classic individual modifiers.

On the next post we will go through the sqlite tools available on the library.

--

--

Alejandro Moya
Codelitt

Mobile developer, Father, geek, this is my first attempt at having a blog, be kind 😄