Skip to content

Instantly share code, notes, and snippets.

@Andrew0000
Created August 9, 2023 14:22
Show Gist options
  • Select an option

  • Save Andrew0000/2dfbbb802ac82528f7797382ca4cb7ce to your computer and use it in GitHub Desktop.

Select an option

Save Andrew0000/2dfbbb802ac82528f7797382ca4cb7ce to your computer and use it in GitHub Desktop.
LazyView
import android.view.View
/**
* Lightweight alternative for [android.view.ViewStub]
*/
class LazyView<T : View>(
private val init: () -> T,
) {
private var view: T? = null
fun getOrNull(): T? = view
fun get(): T {
if (view == null) {
view = init()
}
return view!!
}
fun clear() {
view = null
}
}
// Sample for Fragment
private val someLazyView = LazyView {
SomeView(requireContext()).apply {
binding.rootView.addView(this)
updateLayoutParams<FrameLayout.LayoutParams> {
//
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
someLazyView.clear()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment