Skip to content

Instantly share code, notes, and snippets.

@johnkil
Last active November 25, 2020 10:58
Show Gist options
  • Save johnkil/8b52be2748e1b1039d6fcf354788b1dc to your computer and use it in GitHub Desktop.
Save johnkil/8b52be2748e1b1039d6fcf354788b1dc to your computer and use it in GitHub Desktop.
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
abstract class BindableFragment<VB : ViewBinding>(
private val viewBindingFactory: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : Fragment() {
var binding: VB? = null
private set
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val binding = viewBindingFactory(inflater, container, false)
this.binding = binding
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
fun requireBinding(): VB = checkNotNull(binding)
inline fun withBinding(block: VB.() -> Unit) {
binding?.block()
}
}
class PaymentFragment : BindableFragment<FragmentPaymentBinding>(FragmentPaymentBinding::inflate) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
withBinding {
//...
}
}
}
@Jeff11
Copy link

Jeff11 commented Nov 24, 2020

I would inline fun withBinding(..)

@johnkil
Copy link
Author

johnkil commented Nov 25, 2020

I would inline fun withBinding(..)

@Jeff11 you are right 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment