如何处理 ViewModel 中的配置更改

Posted

技术标签:

【中文标题】如何处理 ViewModel 中的配置更改【英文标题】:How to handle config changes in ViewModel 【发布时间】:2021-06-07 05:18:53 【问题描述】:

我有简单的注册表单。当我输入数据并更改配置时,数据会丢失。我在我的项目中使用 ViewModel,官方文档说 ViewModel 可以自动处理方向变化,但它不会发生。我想如何使用 SaveState 存储数据,或者我在 ViewModel 中犯了一个错误?

片段代码

class StartFragment : Fragment() 
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? 
        val binding: StartFragmentBinding = DataBindingUtil.inflate(
            inflater, R.layout.start_fragment, container, false)
        val application = requireNotNull(this.activity).application

        val dataSource = UsersDatabase.getInstance(application).usersDatabaseDao
        val vm: SavedStateHandle by viewModels()
        val viewModelFactory = StartFragmentViewModelFactory(dataSource, application)

        val startFragmentViewModel =
            ViewModelProvider(
                this, viewModelFactory).get(StartFragmentViewModel::class.java)

        binding.startFragmentViewModel = startFragmentViewModel
        binding.lifecycleOwner = this

        binding.start.setOnClickListener 
                findNavController().navigate(
                    StartFragmentDirections
                        .actionStartFragmentToWebViewFragment())
                startFragmentViewModel.doneNavigation()
            
        return binding.root
    

视图模型

class StartFragmentViewModel(
    val database: UsersDatabaseDao,
    application: Application
) : androidViewModel(application) 
    private var viewModelJob = Job()

    override fun onCleared() 
        super.onCleared()
        viewModelJob.cancel()
    

    private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
    private var user1 = MutableLiveData<User?>()


    private val _navigateToWebView = MutableLiveData<User>()
    val navigateToWebView: LiveData<User>
        get() = _navigateToWebView

    fun doneNavigation() 
        _navigateToWebView.value = null
        uiScope.launch 
            val user = User()
            insert(user)
        
    

    private suspend fun insert(user: User) 
        withContext(Dispatchers.IO) 
            database.insert(user)
        
    

ViewModelFactory

class StartFragmentViewModelFactory (
    private val dataSource: UsersDatabaseDao,
    private val application: Application
) : ViewModelProvider.Factory 
        @Suppress("unchecked_cast")
        override fun <T : ViewModel?> create(modelClass: Class<T>): T 
            if (modelClass.isAssignableFrom(StartFragmentViewModel::class.java)) 
                return StartFragmentViewModel(dataSource, application) as T
            
            throw IllegalArgumentException("Unknown ViewModel class")
        

start_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="startFragmentViewModel"
            type="com.example.leadsdoittest.StartFragmentViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout

        android:layout_
        android:layout_>

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/margin_start"
            android:layout_
            android:layout_
            android:orientation="vertical"
            app:layout_constraintGuide_begin="16dp" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/margin_end"
            android:layout_
            android:layout_
            android:orientation="vertical"
            app:layout_constraintGuide_end="16dp" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/margin_top"
            android:layout_
            android:layout_
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.3" />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_name"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_
            android:layout_
            app:layout_constraintEnd_toEndOf="@id/margin_end"
            app:layout_constraintStart_toStartOf="@id/margin_start"
            app:layout_constraintTop_toTopOf="@id/margin_top">

            <com.google.android.material.textfield.TextInputEditText
                android:layout_
                android:layout_
                android:hint="@string/name" />
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_phone"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_
            android:layout_
            android:layout_marginTop="16dp"
            app:layout_constraintEnd_toEndOf="@id/margin_end"
            app:layout_constraintStart_toStartOf="@id/margin_start"
            app:layout_constraintTop_toBottomOf="@id/input_name">

            <com.google.android.material.textfield.TextInputEditText
                android:layout_
                android:layout_
                android:inputType="phone"
                android:hint="@string/phone_number" />
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_email"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_
            android:layout_
            android:layout_marginTop="16dp"
            app:layout_constraintEnd_toEndOf="@id/margin_end"
            app:layout_constraintStart_toStartOf="@id/margin_start"
            app:layout_constraintTop_toBottomOf="@id/input_phone">

            <com.google.android.material.textfield.TextInputEditText
                android:layout_
                android:layout_
                android:hint="@string/email" />
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.button.MaterialButton
            android:id="@+id/start"
            android:layout_
            android:layout_
            android:layout_marginTop="50dp"
            android:text="@string/start"
            android:textColor="@android:color/white"
            app:layout_constraintEnd_toEndOf="@id/margin_end"
            app:layout_constraintStart_toStartOf="@id/margin_start"
            app:layout_constraintTop_toBottomOf="@+id/input_email" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

【问题讨论】:

【参考方案1】:

视图状态由框架处理,因此您无需自己实现。但是,保存状态取决于每个视图的唯一 ID,因此请尝试为每个 TextInputEditText 添加一个 ID。

【讨论】:

成功了!你为我节省了大量时间。谢谢【参考方案2】:

使用实例变量来恢复旋转后的数据。看:

   class StartFragment  : Fragment() 

    //private lateinit var homeViewModel: HomeViewModel
    var name = ""
    var email = ""
    var phone = ""
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View 
        val binding = FragmentHomeBinding.inflate(inflater)

        binding.etName.doOnTextChanged  text, start, before, count ->
            name = text.toString()
        
        binding.etPhone.doOnTextChanged  text, start, before, count ->
            phone = text.toString()
        
        binding.etEmail.doOnTextChanged  text, start, before, count ->
            email = text.toString()
        
        binding.etName.setText(name)
        binding.etEmail.setText(email)
        binding.etPhone.setText(phone)
        return binding.root
    

【讨论】:

所以我需要 onCreate() 和 onCreateView()?如果我同时使用如何初始化 binding.startFragmentViewModel?因为在 onCreate 中初始化了 startFragmentViewModel? 添加了屏幕截图以显示我的意思。 您使用的是多视图模型吗?你在使用动态数据绑定吗? 片段我只有一个 ViewModel。动态是什么意思? 动态数据绑定,并不是一个新概念。你可能听说过。好的,告诉我一件事 ui 数据被刷新或视图模型数据在旋转后被刷新?

以上是关于如何处理 ViewModel 中的配置更改的主要内容,如果未能解决你的问题,请参考以下文章

MVVM - 如何处理 ViewModel 中由模型组成的匿名类型

如何处理绑定:更改 observableArray 中的数据后的 foreach

如何处理更改密码中的异常?

我应该如何处理响应式设计中的 DOM 更改? [复制]

如何处理 UIAutomation 中的文本通知?

如何处理 Android 应用程序中的版本更改