Skip to content

Instantly share code, notes, and snippets.

@axiel7
Last active February 3, 2023 12:48
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 axiel7/fa88a9c5d55913439a6572a138c7a54f to your computer and use it in GitHub Desktop.
Save axiel7/fa88a9c5d55913439a6572a138c7a54f to your computer and use it in GitHub Desktop.
Android BaseFragment with ViewBinding
import android.content.Context
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 BaseFragment<VB: ViewBinding> : Fragment() {
protected lateinit var safeContext: Context
private var _binding: VB? = null
protected val binding get() = _binding!!
protected abstract val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB
override fun onAttach(context: Context) {
super.onAttach(context)
safeContext = context
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = bindingInflater.invoke(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setup()
}
/**
* Called after onViewCreated
*/
abstract fun setup()
override fun onDestroyView() {
super.onDestroyView()
onDestroyingView()
_binding = null
}
/**
* Called onDestroyView, before binding = null
*/
open fun onDestroyingView() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment