Created
August 9, 2023 14:22
-
-
Save Andrew0000/2dfbbb802ac82528f7797382ca4cb7ce to your computer and use it in GitHub Desktop.
LazyView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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