Created
April 7, 2020 08:16
-
-
Save yaraki/fc5c782afa152c090ff569c3a8473621 to your computer and use it in GitHub Desktop.
This file contains 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
package io.github.yaraki.miscex | |
import android.view.ViewGroup | |
import androidx.databinding.DataBindingUtil | |
import androidx.databinding.ViewDataBinding | |
import androidx.fragment.app.Fragment | |
import androidx.fragment.app.FragmentActivity | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.LifecycleEventObserver | |
/** | |
* Retrieves a data binding handle in an Activity. | |
* | |
* ``` | |
* private val binding: MainActivityBinding by dataBindings() | |
* ``` | |
*/ | |
inline fun <reified BindingT : ViewDataBinding> FragmentActivity.dataBindings() = | |
object : Lazy<BindingT> { | |
private var cached: BindingT? = null | |
override val value: BindingT | |
get() = cached ?: DataBindingUtil.bind<BindingT>( | |
findViewById<ViewGroup>(android.R.id.content).getChildAt(0) | |
)!!.also { cached = it } | |
override fun isInitialized() = cached != null | |
} | |
/** | |
* Retrieves a data binding handle in a Fragment. The returned instance is already set up with the | |
* [androidx.lifecycle.LifecycleOwner]. The field is available only after [Fragment.onViewCreated]. | |
* | |
* ``` | |
* private val binding: HomeFragmentBinding by dataBindings() | |
* | |
* override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | |
* binding.someVariable = ... | |
* } | |
* ``` | |
*/ | |
inline fun <reified BindingT : ViewDataBinding> Fragment.dataBindings() = object : Lazy<BindingT> { | |
private var cached: BindingT? = null | |
private val observer = LifecycleEventObserver { _, event -> | |
if (event == Lifecycle.Event.ON_DESTROY) { | |
cached = null | |
} | |
} | |
override val value: BindingT | |
get() = cached ?: DataBindingUtil.bind<BindingT>(requireView())!!.also { | |
viewLifecycleOwner.lifecycle.addObserver(observer) | |
it.lifecycleOwner = viewLifecycleOwner | |
cached = it | |
} | |
override fun isInitialized() = cached != null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment