Base-Fragment with Hilt

An example of the beautiful Base-Fragment. {ViewBinding, ViewModel, Hilt}

BASE_FRAGMENT {ViewBinding, ViewModel, Hilt}
buildFeatures {
viewBinding = true
}
implementation "androidx.fragment:fragment-ktx:version" // 1.3.4
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
}
}
@AndroidEntryPoint
class UseFragment : BaseFragment<FragmentUseBinding, UseViewModel>() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

binding.root
viewModel.textMethod()
}

Разработчик Android. Фанат, энтузиаст, создатель анимации