Base-Fragment with Hilt
An example of the beautiful Base-Fragment. {ViewBinding, ViewModel, Hilt}
2 min readJun 12, 2021
This is my personal vision, BF and I believe that in BF there should be only ViewBinding and ViewModel, and in this article I will show you how to perfectly implement this with the help of {reflection, ViewBinding, fragment:ktx }.
1️⃣ ViewBinding
path: build.gradle/android { … }
buildFeatures {
viewBinding = true
}
2️⃣ Fragment KTX
path: build.gradle/dependencies{ … }
implementation "androidx.fragment:fragment-ktx:version" // 1.3.4
Required for convenient implementation ViewModel.
3️⃣ BF
abstract class BaseFragment<VB : ViewBinding, VM : ViewModel> : Fragment() {
protected lateinit var binding: VB private set
protected lateinit var viewModel: VM private set
private val type = (javaClass.genericSuperclass as ParameterizedType)
private val classVB = type.actualTypeArguments[0] as Class<VB>
private val classVM = type.actualTypeArguments[1] as Class<VM>
private val inflateMethod = classVB.getMethod(
"inflate",
LayoutInflater::class.java,
ViewGroup::class.java,
Boolean::class.java
)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = inflateMethod.invoke(null, inflater, container, false) as VB
viewModel = createViewModelLazy(classVM.kotlin, { viewModelStore }).value
return binding.root
}
}
4️⃣ Use
@AndroidEntryPoint
class UseFragment : BaseFragment<FragmentUseBinding, UseViewModel>() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.root
viewModel.textMethod()
}
5️⃣ Applause and joy because now you know more, and by the way, read a very useful thing about reflection 😉.
PS. Vel_daN: Love what You DO 💚