活动或片段将在进入splitScreen之后创建viewModel的新实例

时间:2019-04-22 14:51:06

标签: android mvvm kotlin dagger-2

我有一个Activity,其中提供了ViewModel抛出ViewModelFactory。我所有的装饰都是在https://github.com/googlesamples/android-architecture-components之后创建的。

一切正常,但是当我尝试进入分屏显示时,我的活动将我传递给创建ViewModel的新实例。但是,当我关闭拆分屏幕并进入正常模式时,我的活动将返回先前对ViewModel的检查。哪里有问题?

ViewModelFactory

Singleton
class ViewModelFactory @Inject constructor(private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        var creator: Provider<out ViewModel>? = creators.get(modelClass)
        if (creator == null) {
            for (entry in creators.entries) {
                if (modelClass.isAssignableFrom(entry.key)) {
                    creator = entry.value
                    break
                }
            }
        }
        if (creator == null) {
            throw IllegalArgumentException("unknown model class $modelClass")
        }
        try {
            return creator.get() as T
        } catch (e: Exception) {
            Log.d("ERRORR", e.toString())
            throw RuntimeException(e)
        }

    }
}

活动

    class MyActivity: AppCompatActivity(), Injectable, HasSupportFragmentInjector {
        @Inject
        lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>

    lateinit var viewModel: MyViewModel

        @Inject
        lateinit var viewModelFactory: ViewModelFactory

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)

            viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
            val binding: MyLayoutBinding= DataBindingUtil.setContentView(this, R.layout.my_layout)
        }
}

模块

@Module
abstract class ActivityModule {

    @Binds
    abstract fun activity(activity: MainActivity): Activity

    @Binds
    abstract fun bindViewModelFactory(factory: MyViewModelFactory): ViewModelProvider.Factory

    @Binds
    @IntoMap
    @ViewModelKey(MainViewModel::class)
    abstract fun MyViewModel(mainViewModel: MyViewModel): ViewModel



}

清单

<activity
    android:name=".ui.main.MainActivity"
    android:screenOrientation="portrait"
        android:configChanges="orientation|screenSize"
>

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
</activity>

0 个答案:

没有答案