Skip to content

Instantly share code, notes, and snippets.

@houssemzaier
Created February 25, 2021 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save houssemzaier/64077dc6369b53c899566e98dbe6fe24 to your computer and use it in GitHub Desktop.
Save houssemzaier/64077dc6369b53c899566e98dbe6fe24 to your computer and use it in GitHub Desktop.
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)
}
}
@houssemzaier
Copy link
Author


class MainActivity : AppCompatActivity(R.layout.main_activity) {
 private val binding by activityBinding<MainActivityBinding>()

@houssemzaier
Copy link
Author

  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