Skip to content Skip to sidebar Skip to footer

Are Livedata Objects Observable In Xml?

When I bind ObservableField<> objects to a view in XML, changes to the value via set() are immediately reflected in the view. When I bind LiveData<> objects in XML, how

Solution 1:

You can make use of data-binding. https://developer.android.com/topic/libraries/data-binding/

With data binding, your xml will be notified when there is a change in your LiveData. You can also attach an observer to the same live data in your java code.

Hopefully this helps!

Solution 2:

This works for me via data binding, which I assume is what you are using.

You did not provide your code, so I can only guess that perhaps you are not calling setLifecycleOwner() on your binding object (e.g., ActivityMainBinding for an activity_main layout resource). Without that, data binding cannot register an observer.

This sample project shows a layout that uses android:text="@{viewModel.sensorLiveData}" on a TextView. In the activity that uses this layout, I use setLifecycleOwner() to teach the binding about my 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;

publicclassMainActivityextendsFragmentActivity {
  @BindingAdapter("android:text")
  publicstaticvoidsetLightReading(TextView tv, SensorLiveData.Event event) {
    if (event==null) {
      tv.setText(null);
    }
    else {
      tv.setText(String.format("%f", event.values[0]));
    }
  }

  @OverridepublicvoidonCreate(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());
  }
}

And it works like a champ, assuming your device has an ambient light sensor that works.

Post a Comment for "Are Livedata Objects Observable In Xml?"