Created
February 25, 2021 15:36
-
-
Save houssemzaier/64077dc6369b53c899566e98dbe6fe24 to your computer and use it in GitHub Desktop.
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
package com.bravedroid.connecta.presentation.main | |
import android.view.View | |
import android.view.ViewGroup | |
import androidx.databinding.DataBindingUtil | |
import androidx.databinding.ViewDataBinding | |
import androidx.fragment.app.Fragment | |
import androidx.fragment.app.FragmentActivity | |
import kotlin.properties.ReadOnlyProperty | |
class ActivityBindingHelper<T : ViewDataBinding>(private val activity: FragmentActivity) : Lazy<T> { | |
private var binding: T? = null | |
override fun isInitialized(): Boolean = binding != null | |
override val value: T | |
get() = binding ?: DataBindingUtil.bind<T>(getContentView())!!.also { t: T -> | |
t.lifecycleOwner = this.activity | |
binding = t | |
} | |
private fun getContentView(): View = checkNotNull( | |
activity.findViewById<ViewGroup>(android.R.id.content).getChildAt(0) | |
) { | |
"Call setContentView or Use Activity's secondary constructor passing layout res id." | |
} | |
} | |
fun <T : ViewDataBinding> FragmentActivity.activityBinding() = ActivityBindingHelper<T>(this) | |
fun <T : ViewDataBinding> Fragment.dataBinding(): ReadOnlyProperty<Fragment, T> = | |
@Suppress("UNCHECKED_CAST") | |
ReadOnlyProperty<Fragment, T> { refFragment, property -> | |
val hashCode = property.name.hashCode() | |
requireView().getTag(hashCode) as? T | |
?: DataBindingUtil.bind<T>(requireView())!!.also { | |
it.lifecycleOwner = refFragment.viewLifecycleOwner | |
it.root.setTag(hashCode, it) | |
} | |
} |
Author
houssemzaier
commented
Feb 25, 2021
class MainFragment : Fragment(R.layout.main_fragment) {
private val binding: MainFragmentBinding by dataBinding()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment