微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

片段如何通过ViewModelInject将捆绑包传递给viewModel

如何解决片段如何通过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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?