Last active
November 25, 2020 10:58
-
-
Save johnkil/8b52be2748e1b1039d6fcf354788b1dc 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
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 { | |
//... | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would inline fun withBinding(..)