Created
February 27, 2021 18:08
-
-
Save m4kvn/875749cb06508d3d956330a8446876ec to your computer and use it in GitHub Desktop.
FragmentのViewBinding用拡張関数
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
| fun <T : ViewBinding> Fragment.viewBinding(viewBindingFactory: (View) -> T) = | |
| FragmentViewBindingDelegate(this, viewBindingFactory) | |
| class FragmentViewBindingDelegate<T : ViewBinding>( | |
| val fragment: Fragment, | |
| val viewBindingFactory: (View) -> T | |
| ) : ReadOnlyProperty<Fragment, T> { | |
| private var binding: T? = null | |
| private val viewLifecycleOwnerObserver = Observer<LifecycleOwner?> { | |
| if (it == null) binding = null | |
| } | |
| private val observer = object : DefaultLifecycleObserver { | |
| override fun onCreate(owner: LifecycleOwner) { | |
| fragment.viewLifecycleOwnerLiveData.observeForever(viewLifecycleOwnerObserver) | |
| } | |
| override fun onDestroy(owner: LifecycleOwner) { | |
| fragment.viewLifecycleOwnerLiveData.removeObserver(viewLifecycleOwnerObserver) | |
| fragment.lifecycle.removeObserver(this) | |
| } | |
| } | |
| init { | |
| if (fragment.lifecycle.currentState != Lifecycle.State.DESTROYED) { | |
| fragment.lifecycle.addObserver(observer) | |
| } | |
| } | |
| override fun getValue(thisRef: Fragment, property: KProperty<*>): T { | |
| val binding = binding | |
| if (binding != null) return binding | |
| val view = thisRef.view | |
| checkNotNull(view) { | |
| "Should get bindings when the view is not null." | |
| } | |
| return viewBindingFactory(view).also { this.binding = it } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment