Kotlin extensions for Android View

Malwinder Singh
3 min readJul 20, 2019

--

In this article, I shall be sharing with you the following Kotlin extensions for Android View.

Get String resource value

Use this extension to directly get String resource value from a View.

/**
* Extension method to provide simpler access to {@link View#getResources()#getString(int)}.
*/
fun View.getString(stringResId: Int): String = resources.getString(stringResId)

To use this simple call:

textViewName.getString(R.string.name_title)

Show or hide Keyboard

Use this extension to show or hide the soft keyboard from a View

/**
* Extension method to show a keyboard for View.
*/
fun View.showKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
this.requestFocus()
imm.showSoftInput(this, 0)
}
/**
* Try to hide the keyboard and returns whether it worked
* Please note that this is a Context extension.
* https://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard
*/
fun Context.hideKeyboard(): Boolean {
try {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
return inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
} catch (ignored: RuntimeException) { }
return false
}

To use this, simply call:

editTextName.showKeyboard()
context.hideKeyboard()

Show Snackbar

Use these extensions to show a Snackbar from view.

Show Snackbar with message

/**
* Show a snackbar with [message]
*/
fun View.snack(message: String, length: Int = Snackbar.LENGTH_LONG) = snack(message, length) {}

You can also use a @StringRes instead of a String literal.

/**
* Show a snackbar with [messageRes]
*/
fun View.snack(@StringRes messageRes: Int, length: Int = Snackbar.LENGTH_LONG) = snack(messageRes, length) {}

To use the above 2 extensions, simply call:

buttonSubmit.snack(R.string.name_submitted, Snackbar.LENGTH_SHORT)
buttonSubmit.snack(R.string.name_submitted)

Execute function when Snackbar is shown

/**
* Show a snackbar with [message], execute [f] and show it
*/
inline fun View.snack(message: String, @Snackbar.Duration length: Int = Snackbar.LENGTH_LONG, f: Snackbar.() -> Unit) {
val snack = Snackbar.make(this, message, length)
snack.f()
snack.show()
}

/**
* Show a snackbar with [messageRes], execute [f] and show it
*/
inline fun View.snack(@StringRes messageRes: Int, @SuppressLint("Range") @Snackbar.Duration length: Int = Snackbar.LENGTH_LONG, f: Snackbar.() -> Unit) {
val snack = Snackbar.make(this, messageRes, length)
snack.f()
snack.show()
}

To use the above two extensions, simply call:

buttonSubmit.snack(R.string.name_submitted, Snackbar.LENGTH_LONG, {
//TODO: Snackbar is now shown. Make some food :)
}
)

Show or hide a View

You can use these extensions to show (make it VISIBLE) or hide (make it GONE) a View. You can also change the visibility of View under a condition.

/**
* Show the view (visibility = View.VISIBLE)
*/
fun View.show() : View {
if (visibility != View.VISIBLE) {
visibility = View.VISIBLE
}
return this
}

/**
* Show the view if [condition] returns true
* (visibility = View.VISIBLE)
*/
inline fun View.showIf(condition: () -> Boolean) : View {
if (visibility != View.VISIBLE && block()) {
visibility = View.VISIBLE
}
return this
}

/**
* Remove the view (visibility = View.GONE)
*/
fun View.hide() : View {
if (visibility != View.GONE) {
visibility = View.GONE
}
return this
}
Source
/**
* Remove the view if [predicate] returns true
* (visibility = View.GONE)
*/
inline fun View.hideIf(predicate: () -> Boolean) : View {
if (visibility != View.GONE && block()) {
visibility = View.GONE
}
return this
}

To use the above extensions, simply call:

buttonSubmit.hide()
buttonSubmit.show()
buttonSubmit.showIf {
editTextName.text != null
}
buttonSubmit.hideIf {
editTextName.text == null
}

Get Bitmap from View

Use this extension to get Bitmap from View

/**
* Extension method to get a view as bitmap.
*/
fun View.getBitmap(): Bitmap {
val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bmp)
draw(canvas)
canvas.save()
return bmp
}

To use the above extension, simply call:

val profileImageBitmap = imageViewProfile.getBitmap()

Safe (Debounce) Click Listener to prevent multiple rapid clicks

This is an interesting Kotlin extension. This extension solves the problem of “rapid clicks” on view. When the view is tapped rapidly, you can allow only first click to perform click action and prevent all other clicks.

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 🥰

Buy me a coffee 🥰

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! 🙂

--

--

Malwinder Singh

Flutter, Kotlin & Android. Worked on projects of Emerson and Omron, 50k+ views on this blog, 6k+ repo on StackOverflow, Drone startup linkedin.com/in/malwinder