- 我有一个由 3 个不同的导航图使用的通用片段。这个片段有 3 个不同的 navGraphViewModels 但只使用其中一个,无论使用它们的片段 ID 调用
它,这不是一个好的设计。我需要使这个片段更通用
- 我正在实现这 3 个 navGraphViewModels,其中 2 个是不必要的。(因为你不能在不实例化这些 navGraphViewModels 的情况下声明。)请任何优秀的架构师或程序设计师都可以为我找到解决方案。
@AndroidEntryPoint
class CommonFragment: BaseFragment<CommonFragmentBinding>() {
//todo should be implemented more generic
private val bookSharedViewModel: BookSharedViewModel by navGraphViewModels(R.id.book)
private val tripSharedViewModel: TripsSharedViewModel by navGraphViewModels(R.id.trips)
private val homeSharedViewModel: HomeSharedViewModel by navGraphViewModels(R.id.home)
private val viewModel: CommonFragmentViewModel by viewModels()
private var label: String? = null
override fun inflateBinding(
inflater: LayoutInflater,
container: ViewGroup?
): CommonFragmentBinding =
CommonFragmentBinding.inflate(
inflater,
container,
false
)
@SuppressLint("RestrictedApi")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
label = findNavController().previousBackStackEntry?.destination?.displayName
viewModel.editTripModel = getFromSharedModel()
}
private fun getFromSharedModel() = when (label) {
"${BuildConfig.APPLICATION_ID}:id/bookFragment" -> bookSharedViewModel.editTripModel
"${BuildConfig.APPLICATION_ID}:id/tripEditFragment" -> tripSharedViewModel.editTripModel
"${BuildConfig.APPLICATION_ID}:id/homeEditFragment" -> homeSharedViewModel.editTripModel
else -> null
}