Last active
February 3, 2023 12:48
-
-
Save axiel7/fa88a9c5d55913439a6572a138c7a54f to your computer and use it in GitHub Desktop.
Android BaseFragment with ViewBinding
This file contains 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.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