Skip to content

Instantly share code, notes, and snippets.

@Bloody-Badboy
Created March 2, 2021 07:42
Show Gist options
  • Save Bloody-Badboy/175daf3a9b73031e2cdd6463ace71863 to your computer and use it in GitHub Desktop.
Save Bloody-Badboy/175daf3a9b73031e2cdd6463ace71863 to your computer and use it in GitHub Desktop.
ViewBinding Fragment that destroy binding when view destroyed to prevent memory leaks
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
open class BaseFragment<out Binding : ViewBinding>(@LayoutRes contentLayoutId: Int) :
Fragment(contentLayoutId) {
private var _binding: Binding? = null
val binding: Binding
get() = _binding ?: throw IllegalStateException(
"Fragment $this binding cannot be accessed before onCreateView() or " +
"after onDestroyView() is called."
)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view = super.onCreateView(
inflater,
container,
savedInstanceState
) ?: throw IllegalStateException("Fragment $this did not return a View from onCreateView()")
_binding = DataBindingUtil.bind(view)
return binding.root
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment