Android Kotlin:使用XML中的数据绑定,可变的实时数据更改不会反映/更新布局

时间:2019-11-11 11:55:07

标签: android kotlin android-databinding android-mvvm mutablelivedata

我创建了示例项目,以将Android数据绑定与xml布局结合使用。 MVVM也用于可变实时数据。 屏幕布局具有相同的布局中的开关小部件和线性布局。我只是想隐藏/显示switch小部件状态变化时的linearlayout。一切都按照概念进行编码。如果在视图模型中分配,它也可以正常使用开关小部件的默认值(选中= true / false)。但它在运行时不起作用。

预期结果:开关状态改变。线性布局应隐藏/显示 true:显示-linearlayout false:隐藏-linearlayout

很遗憾,它无法正常工作。有人可以帮我找到问题吗?

activity_first.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"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewModel"
            type="info.phone.android.com.testapplication.FirstViewModel" />
    </data>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".FirstActivity">

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </com.google.android.material.appbar.AppBarLayout>

        <include
            android:id="@+id/content"
            app:viewModel="@{viewModel}"
            layout="@layout/content_first" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            app:srcCompat="@android:drawable/ic_dialog_email" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>

content_first.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"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <import type="android.view.View" />

        <variable
            name="viewModel"
            type="info.phone.android.com.testapplication.FirstViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="24dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".FirstActivity"
        tools:showIn="@layout/activity_first">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="48dp"
            android:layout_marginLeft="48dp"
            android:text="Power"
            app:layout_constraintBottom_toBottomOf="@+id/switchCompat"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/switchCompat" />

        <androidx.appcompat.widget.SwitchCompat
            android:id="@+id/switchCompat"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="@={viewModel.switchPower}"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="24dp"
            android:layout_marginStart="24dp"
            android:layout_marginLeft="24dp"
            android:layout_marginEnd="24dp"
            android:layout_marginRight="24dp"
            android:gravity="center"
            android:orientation="horizontal"
            android:visibility="@{viewModel.switchPower ? View.VISIBLE : View.GONE}"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/switchCompat">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="24dp"
                android:layout_marginStart="48dp"
                android:layout_marginLeft="48dp"
                android:text="Child Switch" />

            <androidx.appcompat.widget.SwitchCompat
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />


        </LinearLayout>

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

FirstActivity.kt

import android.os.Bundle
import android.util.Log
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import info.phone.android.com.testapplication.databinding.ActivityFirstBinding

import kotlinx.android.synthetic.main.activity_first.*
import timber.log.Timber

class FirstActivity : AppCompatActivity() {

    lateinit var binding: ActivityFirstBinding
    lateinit var viewModel: FirstViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_first)
        viewModel = ViewModelProviders.of(this).get(FirstViewModel::class.java)
        binding.viewModel = viewModel
        setSupportActionBar(binding.toolbar)

        viewModel.switchPower.observe(this, Observer {
            Timber.e("switchPower : $it")
        })

        binding.fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }
    }
}

ViewModel:FirstViewModel.kt

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData

class FirstViewModel(application: Application): AndroidViewModel(application) {

    var switchPower = MutableLiveData<Boolean>()

    init {
        switchPower.value = false // true:false -> working properly
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在onCreate()中设置binding.setLifecycleOwner(this)。