更改 LiveData 时 DataBinding 不会更新值

DataBinding doesn't update value when changing LiveData

我希望按下按钮时值增加并将其写入textview。 但是,下面的代码将增加的值显示为 Log 但是,在屏幕上,textview 中的值不会改变。 我不确定出了什么问题。知道的请告诉我

Fragment.kt

class SettingFragment : Fragment(), View.OnClickListener {

    companion object {
        fun newInstance() = SettingFragment()
        private val TAG = "SettingFragment"
    }

    private lateinit var viewModel: SettingViewModel
    private lateinit var binding: FragmentSettingBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_setting, container, false)
        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(SettingViewModel::class.java)
        binding.lifecycleOwner = this
        binding.button.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        viewModel.increase()
        Log.d(TAG, "Log Data" + viewModel.testInt.value)
    }

}

FragmentViewModel

class SettingViewModel : ViewModel() {


    val testInt: MutableLiveData<Int> = MutableLiveData()

    init {
        testInt.value = 0
    }

    fun increase() {
        testInt.value = testInt.value?.plus(1)
    }
}

fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <data>
        <variable
            name="viewModel"
            type="com.example.ui.setting.SettingViewModel" />
    </data>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".ui.setting.SettingFragment">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{String.valueOf(viewModel.testInt)}" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
</layout>
    <variable
        name="viewModel"
        type="com.example.ui.setting.SettingViewModel" />

viewModel 变量未以编程方式绑定到某个变量。因此,当值增加时,它不会反映到布局中。

要修复此问题,请将片段的 viewModel 设置为此值:

    viewModel = ViewModelProvider(this).get(SettingViewModel::class.java)
    binding.viewModel = viewModel // <<<<< Here is the change
    binding.lifecycleOwner = this
    binding.button.setOnClickListener(this)

旁注:

你不应该使用 onActivityCreated() 因为它是 deprecated as of API level 28; you can normally its part of code to onCreateView(). And you can 用于其他替代。