是否可以在XML中观察LiveData对象?

时间:2018-12-06 19:37:52

标签: java android kotlin android-databinding android-livedata

当我将ObservableField<>对象绑定到XML视图时,通过set()对值的更改将立即反映在视图中。但是,当我以XML绑定LiveData<>对象时,将呈现初始值,但通过value=进行的更改对视图没有影响。他们 传递给科特林观察员。

我假设LiveData可以像XML绑定中的Observable*类一样工作。不是吗?如果我需要同时观察XML和Kotlin中的值,是否真的需要创建两个可观察对象?

2 个答案:

答案 0 :(得分:1)

您可以利用数据绑定。 https://developer.android.com/topic/libraries/data-binding/

使用数据绑定,当LiveData中发生更改时,将通知您的xml。您还可以在Java代码中将观察者附加到相同的实时数据。

希望这会有所帮助!

答案 1 :(得分:0)

这通过数据绑定对我有用,我认为这是您正在使用的数据。

您没有提供代码,所以我只能猜测您可能没有在绑定对象上调用setLifecycleOwner()(例如,ActivityMainBinding是布局资源的activity_main)。否则,数据绑定将无法注册观察者。

This sample project显示a layoutandroid:text="@{viewModel.sensorLiveData}"上使用TextView。在使用这种布局的活动中,我使用setLifecycleOwner()来教授关于我的FragmentActivity的绑定:

/***
  Copyright (c) 2013-2017 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  Covered in detail in the book _Android's Architecture Components_
    https://commonsware.com/AndroidArch
 */

package com.commonsware.android.livedata;

import android.arch.lifecycle.ViewModelProviders;
import android.databinding.BindingAdapter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.commonsware.android.livedata.databinding.MainBinding;

public class MainActivity extends FragmentActivity {
  @BindingAdapter("android:text")
  public static void setLightReading(TextView tv, SensorLiveData.Event event) {
    if (event==null) {
      tv.setText(null);
    }
    else {
      tv.setText(String.format("%f", event.values[0]));
    }
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    MainBinding binding=MainBinding.inflate(getLayoutInflater());
    SensorViewModel vm=ViewModelProviders.of(this).get(SensorViewModel.class);

    binding.setViewModel(vm);
    binding.setLifecycleOwner(this);
    setContentView(binding.getRoot());
  }
}

假设您的设备具有正常工作的环境光传感器,它的工作原理就像冠军。