如何解决片段如何通过ViewModelInject将捆绑包传递给viewModel
我使用hilt将所有想要的东西注入到viewmodel中,我发现通过@viewmodelInject通过hilt支持SavedStateHandle,因此如果需要的话,可以将传递给它的任何捆绑数据取回。
class Testviewmodel @viewmodelInject constructor(
private val testRepository: TestRepository,@Assisted private val state: SavedStateHandle
) : viewmodel() {
val testItem = state["test"] ?: "defaultValue"
}
@AndroidEntryPoint
class TestFragment : Fragment() {
private val viewmodel: Testviewmodel by viewmodels() // How to pass bundle to the init viewmodel?
override fun onCreateView(
inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?
): View? {
val binding = FragmentTestBinding.inflate(inflater)
binding.lifecycleOwner = this
binding.viewmodel = viewmodel
...
}
}
似乎是使用viewmodelFactory通过bundle初始化viewmodel的方法。
interface viewmodelAssistedFactory<T : viewmodel> {
fun create(state: SavedStateHandle): T
}
class TestviewmodelFactory @Inject constructor(
private val testRepository: TestRepository
) : viewmodelAssistedFactory<Testviewmodel> {
fun create(handle: SavedStateHandle) {
return Testviewmodel(handle,testRepository)
}
}
class Testviewmodel(
private val state: SavedStateHandle
private val testRepository: TestRepository,) : viewmodel() {
val id = state["test"] ?: "defaultValue"
}
解决方法
如果我正确理解了您的问题,那么您想实例化ViewModel并传递一个捆绑包,我怀疑Injecting ViewModel with Dagger Hilt文章可能会有所帮助。
滚动到底部,有2个示例,其中使用各种方法来实例化ViewModel,特别是其中一个正在传递Bundle。
这是另一个很好的资源:No more Factory Needed for ViewModel with Dependencies。
这是我所做的,也许不够优雅,但是效果很好:
class dataViewModel @ViewModelInject constructor(
val stateData: StateData,@Assisted private val savedStateHandle: SavedStateHandle
): ViewModel() {
然后,要实例化viewModel,您需要一个模块定义:
@Module
@InstallIn(ApplicationComponent::class)
class StateDataModule {
@Singleton
@Provides
fun provideStateData(): StateData {
return StateData(null,null)
}
}
然后,在使用它的类中,我设置了值,并且ViewModel保留了所有实例和跨活动的值(这是我这样做的主要原因)。
dataViewModel.stateData.[property] = blah
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。