Kotlin Extensions for Context, Float, Integer, and Log
Hello friends 😊
In this post, I shall share you some of the useful Kotlin extensions on topics of:
Context
, Float
, Integer
and Log
Please make sure you know about Kotlin’s default parameters in function before reading this article.
Context extensions
Display a toast
fun Context.toast(message: CharSequence, isLengthLong: Boolean = true) =
Toast.makeText(
this, message, if (isLengthLong) {
Toast.LENGTH_LONG
} else {
Toast.LENGTH_SHORT
}
).show()
To use this, simply call:
toast(response?.message)
In the above example, response
is the response you received from API call and message
is a String
parameter in it.
You can also use String resource instead of a CharSequence
, like this:
fun Context.toast(@StringRes message: Int, isLengthLong: Boolean) {
toast(getString(message), isLengthLong)
}
To use this, simply call:
toast(R.string.message_success, false)
Show an Alert Dialog
To use this extension, please add this dependency to your Android project:
implementation 'com.afollestad.material-dialogs:core:3.1.0' //Replace 3.1.0 with latest version found here
And also don’t forget to add this String resource value:
<string name="ok">OK</string>
Extension:
fun Context.simpleAlert(@StringRes message: Int) {
MaterialDialog(this).show {
message(res = message)
positiveButton(R.string.ok)
message(res = message)
}
}
To use this, you can simply call:
simpleAlert(R.string.your_query_is_submitted)
Output:
Another one, but this time with lots of customization like You can add title, message, positive and negative button texts, and event callback for the positive button click.
fun Context.alert(
@StringRes titleRes: Int? = null, @StringRes message: Int, @StringRes positiveBtn: Int, @StringRes negativeBtn: Int,
action: () -> Unit
) {
MaterialDialog(this).show {
titleRes?.let { title(it) }
message(res = message)
positiveButton(positiveBtn, click = object : DialogCallback {
override fun invoke(p1: MaterialDialog) {
action()
}
})
negativeButton(negativeBtn)
}
}
You can simply use it like:
alert(R.string.are_you_sure, R.string.lose_access_question, R.string.yes, R.string.no) {
//TODO: Handle YES button press
}
Output:
Find the Activity
You can use this extension function to find an activity in which a fragment or view is present:
tailrec fun Context.activity(): Activity? = when {
this is Activity -> this
else -> (this as? ContextWrapper)?.baseContext?.activity()
}
Here’s how you can use it:
textview.context.activity()
, dashboardFragment.requireContext().activity()
In the above example, textView
is a TextView
and dashboardFragment
is a Fragment
.
Float extensions
Round off to 2 decimal places
Following extension rounds off float value to two decimal places and returns String
.
fun Float.roundOff(): String {
val df = DecimalFormat("##.##")
return df.format(this)
}
For example:
33.36631f.roundOff() //Returns 33.37
41f.roundOff() //Returns 41.00
93.3211f.roundOff() //Returns 93.32
and so on...
Integer extensions
Appending Ordinal
This extension appends ordinal to an integer.
fun Int.appendOrdinal(): String {
return ordinalOf(this)
}
private fun ordinalOf(i: Int) = "$i" + if (i % 100 in 11..13) "th" else when (i % 10) {
1 -> "st"
2 -> "nd"
3 -> "rd"
else -> "th"
}
For example:
1.appendOrdinal() //Returns 1st
22.appendOrdinal() //Returns 22nd
Pixel to DP and DP to Pixel
This extension is very useful. It converts Pixel to DP values and vice versa
val Int.pxTodp: Int
get() = (this / Resources.getSystem().displayMetrics.density).toInt()
val Int.dpTopx: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
For example:
100.pxTodp
20.dpToPx
Log extensions
Simplify Logs
Debug and Error Log:
fun Any.logd(message: String?) {
Log.d(this::class.java.simpleName, "" + message)
}
fun Any.loge(message: String?) {
Log.e(this::class.java.toString(), "" + message)
}
You can use them simply like:
logd("Success")
loge("404 Not Found")
loge() or logd() //These will also show in your Logcat.
Update: Following is not a Kotlin extension but very useful. Simple try-catch handler:
//Returns true if no exception was caught. Otherwise, it logs the exception and returns false
fun tryCatch(body: () -> Unit): Boolean {
return try {
body()
true
} catch (e: Throwable) {
body.loge(e.message)
false
}
}
You can use them like:
val isValid = tryCatch {
val na = 1/0
}
In the above example, the exception is logged and the value of isValid
becomes false.
Hope you liked this article!
Medium does not allow Indian writers to monetize currently 😭. Please support this blog by contributing here: https://www.patreon.com/malwinder 🥰
Even a small contribution would help 😍
If you have any questions, then please write down a response in the response section.
If you liked this article, then please press the 👏 icon.
Thank you!
Peace! 🙂