DEV Community

Bigyan Thapa
Bigyan Thapa

Posted on

Common android utility functions made easier with kotlin-extensions

As kotlin has taken over most of Android development ecosystem, by now we all are aware of all the goodies that kotlin offers. One of the most liked goodies is extension-functions.
Following are some of the extension-functions that come in handy in day-to-day android application development.

Showing/ hiding views

fun View.visibleOrGone(show: Boolean = false) {
  this.visibility = if(show) {
    View.VISIBLE
  } else {
    View.GONE
  }

Hide Keyboard

fun View.hideKeyboard() {
  (context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.let { inputManager -> 
    inputManager.hideSoftInputFromWindow(windowToken, 0)
  }
}

EditText after text changed

We can pass the function to be performed after edit text input changes as closure.

fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
  this.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable?) {
      afterTextChanged.invoke(s?.toString())
    }
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { // na
    }
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { // na
    }
  })
}

RecyclerView set divider

dividerResId is the divider drawable if we have to provide custom divider.

fun RecyclerView.setDivider(dividerResId: Int? = null, orientation: Int = DividerItemDecoration.VERTICAL) {

  val dividerItemDecoration = DividerItemDecoration(this.context, orientation)

  dividerResId?.let { resId ->
    this.context.getDrawableResource(resId)
      ?.let { divider ->
        dividerItemDecoration.setDrawable(divider)
      }
  }
  this.addItemDecoration(dividerItemDecoration)
}

Accessing resources with ContextCompact

fun Context.getColorResource(colorRes: Int): Int {
  return ContextCompat.getColor(this, colorRes)
}

fun Context.getDrawableResource(drawableRes: Int): Drawable? {
  return ContextCompat.getDrawable(this, drawableRes)
}

TextView extensions to set drawable

fun TextView.setDrawable(
  @DrawableRes
  drawable: Int, start: Boolean, end: Boolean, top: Boolean, bottom: Boolean
) {
  when {
    start  -> this.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, 0, 0, 0)
    end    -> this.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, drawable, 0)
    top    -> this.setCompoundDrawablesRelativeWithIntrinsicBounds(0, drawable, 0, 0)
    bottom -> this.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, drawable)
  }
  this.compoundDrawablePadding = 8
}

I hope this will be helpful. I will add more in future. Please provide feedback in comments.

Top comments (0)