7

我正在尝试使用Jetpack tutorial在片段和活动之间创建共享注入视图模型。

共享视图模型成功注入到父级 MyActivity 中,但是当渲染子级时,由于依赖注入失败,应用程序崩溃。我在下面提供了创建问题的代码。

提供会话管理器:

@InstallIn(ApplicationComponent::class)
@Module
class AppModule {
    @Provides
    @Singleton
    fun provideSessionManager(
        networkClient: NetworkClient
    ): SessionManager {
        return SessionManager(networkClient)
    }
}

注入共享视图模型:

class SharedViewModel @ViewModelInject constructor(
    private var sessionManager: SessionManager
) : ViewModel() {

    var name = MutableLiveData<String>("Shared View Model")
}

并且被父活动和子片段使用。

class MyActionFragment() : Fragment() {
    private val viewModel: SharedViewModel by viewModels()
    override fun onActivityCreated(savedInstanceState: Bundle?) {
       super.onActivityCreated(savedInstanceState)
       Timber.d("View Model Name 1: ${viewModel.name.value}") // This line crashes
    }
}
class MyActivity : AuthenticatedBaseActivity() {
    private val viewModel: SharedViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Timber.d("View Model Name 2: ${viewModel.name.value}") // This line prints
    }
}

但是,当代码运行时,请注意活动创建了 ViewModel 并访问了它的值,但是当片段尝试这样做时,应用程序崩溃了:

**D/MyActivity: View Model Name 2: Shared View Model**
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.xxx.xxx, PID: 16630
    java.lang.RuntimeException: Cannot create an instance of class com.xxx.xxx.ui.main.SharedViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54)
        at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
        at com.xxx.xxx.ui.main.MyActionFragment.getViewModel(Unknown Source:2)
        at com.xxx.xxx.ui.main.MyActionFragment.onActivityCreated(**MyActionFragment.kt:140**)
        at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2718)

此外,当我删除注入的 Hilt 依赖项时sessionManager,片段和视图模型的创建没有问题。

没有运气就关注了这篇文章

非常感谢有关使用共享模型的 Hilt 视图模型依赖注入的任何帮助!谢谢!

4

3 回答 3

17

您可以在Fragment中使用扩展功能:

class MyFragment: Fragment() {
    private val viewModel: SharedViewModel by activityViewModels()
}

活动中:

class MyActivity : Activity() {
    private val viewModel: SharedViewModel by viewModels()
}
于 2021-02-19T11:59:53.383 回答
8

您必须提供所有依赖项,在您的情况下未提供 NetworkClient

@Module
@InstallIn(ApplicationComponent::class)
object AppModule {

    @Singleton
    @Provides
    fun provideSessionManager(
        networkClient: NetworkClient
    ): SessionManager = SessionManager(networkClient)

    @Singleton
    @Provides
    fun provideNetworkClient() = NetworkClient()
}

在 Activity 或 Fragment 中使用 @AndroidEntryPoint

@AndroidEntryPoint
class MyActionFragment() : Fragment()



@AndroidEntryPoint
class MyActivity : AuthenticatedBaseActivity()
于 2020-07-24T21:56:51.833 回答
6

在活动和片段之间共享数据。使用下面的代码。Hilt doc 对我也不起作用。

活动中

    private val vm by viewModels<StartVM>()

在片段中

private val vm: StartVM by lazy {
    obtainViewModel(requireActivity(), StartVM::class.java, defaultViewModelProviderFactory)
}

Kotlin 扩展

fun <T : ViewModel> Fragment.obtainViewModel(owner: ViewModelStoreOwner,
    viewModelClass: Class<T>,
    viewmodelFactory: ViewModelProvider.Factory
) =
    ViewModelProvider(owner, viewmodelFactory).get(viewModelClass)
于 2020-11-14T06:52:16.990 回答