Created
May 30, 2025 22:36
-
-
Save devapro/7a556f5f5181bdc9d074e92009873c23 to your computer and use it in GitHub Desktop.
Fragment View Binding
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 | |
| import androidx.fragment.app.Fragment | |
| import androidx.lifecycle.DefaultLifecycleObserver | |
| import androidx.lifecycle.Lifecycle | |
| import androidx.lifecycle.LifecycleOwner | |
| import androidx.viewbinding.ViewBinding | |
| import kotlin.properties.ReadOnlyProperty | |
| import kotlin.reflect.KProperty | |
| inline fun <reified T : ViewBinding> Fragment.viewBinding() = FragmentViewBindingDelegate(T::class.java, this) | |
| class FragmentViewBindingDelegate<T : ViewBinding>( | |
| bindingClass: Class<T>, | |
| private val fragment: Fragment | |
| ) : ReadOnlyProperty<Fragment, T> { | |
| /** | |
| * initiate variable for binding view | |
| */ | |
| private var binding: T? = null | |
| /** | |
| * get the bind method from View class | |
| */ | |
| private val bindMethod = bindingClass.getMethod("bind", View::class.java) | |
| @Suppress("UNCHECKED_CAST") | |
| override fun getValue(thisRef: Fragment, property: KProperty<*>): T { | |
| binding?.let { return it } | |
| /** | |
| * Adding observer to the fragment lifecycle | |
| */ | |
| fragment.lifecycle.addObserver(object : DefaultLifecycleObserver { | |
| override fun onCreate(owner: LifecycleOwner) { | |
| fragment.viewLifecycleOwnerLiveData.observe(fragment) { viewLifecycleOwner -> | |
| viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver { | |
| override fun onDestroy(owner: LifecycleOwner) { | |
| /** | |
| * Clear the binding when Fragment lifecycle called the onDestroy | |
| */ | |
| binding = null | |
| } | |
| }) | |
| } | |
| } | |
| }) | |
| /** | |
| * Checking the fragment lifecycle | |
| */ | |
| val lifecycle = fragment.viewLifecycleOwner.lifecycle | |
| if (!lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) { | |
| error("Cannot access view bindings. View lifecycle is ${lifecycle.currentState}!") | |
| } | |
| /** | |
| * Bind layout | |
| */ | |
| val invoke = bindMethod.invoke(null, thisRef.requireView()) as T | |
| return invoke.also { this.binding = it } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment