Let's take a look at some examples of how Android KTX can help you write more natural and concise Kotlin code.
Code Samples Using Android KTX
String to Uri
Let's start with this simple example. Normally, you'd call Uri.parse(uriString). Android KTX adds an extension function to the String class that allows you to convert strings to URIs more naturally.
val uri = Uri.parse(myUriString) | val uri = myUriString.toUri() |
Edit SharedPreferences
Editing SharedPreferences is a very common use case. The code using Android KTX is slightly shorter and more natural to read and write.
sharedPreferences.edit() | sharedPreferences.edit { |
Translating path difference
In the code below, we translate the difference between two paths by 100px.
val pathDifference = Path(myPath1).apply { | val pathDifference = myPath1 - myPath2 |
Action on View onPreDraw
This example triggers an action with a View's onPreDraw callback. Without Android KTX, there is quite a bit of code you need to write.
view.viewTreeObserver.addOnPreDrawListener( |
view.doOnPreDraw { actionToBeTriggered() } |
There are many more places where Android KTX can simplify your code. You can read the . When the API has stabilized and we can commit to API compatibility, we plan to release Android KTX as part of the Android Support Library.
We look forward to building Android KTX together with you. Happy Kotlin-ing!
SOCIAL SHARE CARD GENERATOR