更改ViewModel值后,UI未更新

时间:2018-12-31 10:57:53

标签: android android-databinding android-livedata android-viewmodel

我创建了示例应用程序来演示我的问题:

TextViewButton的文本视图可见性已绑定到viewModel.bar

我希望按钮在单击时切换viewModel.bar的值,并且用户界面也要更新。

但是,这没有发生。值已更改,但用户界面未更新。

布局文件:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="android.view.View"/>
        <variable name="viewModel"
                  type="com.example.bindingone.MainViewModel"/>
    </data>

    <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity">

        <TextView
                android:id="@+id/text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hello World"
                android:visibility="@{viewModel.bar ? View.VISIBLE : View.GONE}"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"/>

        <Button
                android:text="Update UI"
                android:onClick="clicked"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

    </android.support.constraint.ConstraintLayout>

</layout>

MainActivity文件:

class MainActivity : AppCompatActivity() {

    private val viewModel = MainViewModel()

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.viewModel = viewModel
    }

    fun clicked(v: View) {
        viewModel.bar.value = viewModel.bar.value?.not() ?: false
    }
}

MainViewModel文件:

class MainViewModel : ViewModel() {
    var bar = MutableLiveData<Boolean>()
}

1 个答案:

答案 0 :(得分:7)

创建绑定后,添加此行binding.setLifecycleOwner(this)

/**
 * Sets the {@link LifecycleOwner} that should be used for observing changes of
 * LiveData in this binding. If a {@link LiveData} is in one of the binding expressions
 * and no LifecycleOwner is set, the LiveData will not be observed and updates to it
 * will not be propagated to the UI.
 *
 * @param lifecycleOwner The LifecycleOwner that should be used for observing changes of
 *                       LiveData in this binding.
 */
@MainThread
public void setLifecycleOwner(@Nullable LifecycleOwner lifecycleOwner)