Skip to content

Instantly share code, notes, and snippets.

@lgawin
Created May 6, 2020 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lgawin/2636ce0442d4bfb976df16e146e57757 to your computer and use it in GitHub Desktop.
Save lgawin/2636ce0442d4bfb976df16e146e57757 to your computer and use it in GitHub Desktop.
Delegate for finding view by id
import android.app.Activity
import android.view.View
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
fun <T : View> Activity.findView(@IdRes res : Int) : Lazy<T> {
@Suppress("UNCHECKED_CAST")
return lazy(LazyThreadSafetyMode.NONE){ findViewById<T>(res) }
}
fun <T : View> View.findView(@IdRes res : Int) : Lazy<T> {
@Suppress("UNCHECKED_CAST")
return lazy(LazyThreadSafetyMode.NONE){ findViewById<T>(res) }
}
fun <T : View> Fragment.findView(@IdRes res : Int) : Lazy<T> {
@Suppress("UNCHECKED_CAST")
return lazy(LazyThreadSafetyMode.NONE){ requireView().findViewById<T>(res) }
}
@lgawin
Copy link
Author

lgawin commented May 6, 2020

Usage: e.g. declare (delegated) property in Fragment

val searchQueryView: EditText by findView(R.id.search_text)

It can also be used for views. E.g. in ViewHolder declare:

val text1: TextView by itemView.findView(android.R.id.text1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment