Skip to content

Instantly share code, notes, and snippets.

@Nilzor
Last active August 29, 2022 19:22
Show Gist options
  • Save Nilzor/13ffe6216b4a444011bee48de5796bce to your computer and use it in GitHub Desktop.
Save Nilzor/13ffe6216b4a444011bee48de5796bce to your computer and use it in GitHub Desktop.
Useful binding adapters
object GeneralBindingAdapters {
/**
* To allow binding image resource Int in addition to Drawable.
* Saves you from depending on Resouces in the ViewModel,
*/
@JvmStatic
@BindingAdapter("android:src")
fun setImageResource(imageView: ImageView, resource: Int) {
imageView.setImageResource(resource)
}
/** Set visibility on a View to VISIBLE or GONE depending on Boolean value */
@JvmStatic
@BindingAdapter("visibleOrGone")
fun setViewVisibleOrGoneFromBoolean(view: View, show: Boolean) {
view.visibility = if (show) View.VISIBLE else View.GONE
}
/** Set visibility on a View to VISIBLE or INVISIBLE depending on Boolean value */
@JvmStatic
@BindingAdapter("visibleOrInvisible")
fun setViewVisibleOrInvislbleFromBoolean(view: View, show: Boolean) {
view.visibility = if (show) View.VISIBLE else View.INVISIBLE
}
/** Hides the view by setting Visibility.GONE if the object referenced is NULL */
@JvmStatic
@BindingAdapter("goneIfNull")
fun setViewVisibleOrGoneFromObject(view: View, obj: Any?) {
view.visibility = if (obj != null) View.VISIBLE else View.GONE
}
/**
* Bind to function without input parameters for a click listener.
* Stops you from getting those pesky "unused variable" warnings all over
* the place when "view: View" is unused.
*/
@JvmStatic
@BindingAdapter("onClick")
fun onClick(view: View, action: (() -> Unit)?) {
view.setOnClickListener {
action?.invoke()
}
}
/**
* Binding to "android:string" will crash if the int value is 0. This will not.
*/
@JvmStatic
@BindingAdapter("android:text")
fun setStringFromRes(textView: TextView, @StringRes res: Int) {
val textToSet = if (res == 0) "" else textView.resources.getString(res)
if (textView.text != textToSet) textView.text = textToSet
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment