首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >与DataBinding一起使用时,LiveData不会通知UI更改

与DataBinding一起使用时,LiveData不会通知UI更改
EN

Stack Overflow用户
提问于 2018-09-28 03:40:22
回答 1查看 2.8K关注 0票数 1

当与DataBinding一起使用时,我想随着LiveData的变化而改变UI。但是,当LiveData发生变化时,它并没有反映出UI的变化。

MainViewModel.java

代码语言:javascript
运行
复制
public class MainViewModel extends AndroidViewModel {
    /**
     * Boolean variable to see whether user is ClockedIn or ClockedOut
     */
    public MutableLiveData<Boolean> isClockedIn;

    public MainViewModel(Application application) {
        super(application);
        isClockedIn = new MutableLiveData<>();
        //...
        calculateClockedInOrNot(PreferencesManager.getString(mContext,PreferencesManager.CLOCK_STATUS_KEY));
    }

    /**
     * An utility function to calculate whether user is clocked in or clocked out,
     * this function is also called within this ViewModel after an api hit
     *
     * if string == "CLOCKED_OUT" or string == "mobileEventType.CLOCK_OUT" => user is clocked out
     * else user is clocked in
     */
    private void calculateClockedInOrNot(String string) {
        if (string.equals("CLOCKED_OUT") || string.equals("mobileEventType.CLOCK_OUT")) {
            //user is clocked out
            isClockedIn.setValue(false);
        } else {
            //user is clocked in
            isClockedIn.setValue(true);
        }
    }
    //getter function
    public MutableLiveData<Boolean> isClockedIn() {
        return isClockedIn;
    }
    //other function left for brevity
}

MainActivity.java

代码语言:javascript
运行
复制
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Obtain the ViewModel component.
    mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
    // Inflate view and obtain an instance of the binding class.
    ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    // Assign the component to a property in the binding class.
    binding.setData(mainViewModel);
}

activity_main.xml

代码语言:javascript
运行
复制
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools">

<data>

    <variable
        name="data"
        type="com.app.bidunity.viewmodel.MainViewModel" />
</data>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/img_hight_location"
            android:adjustViewBounds="true"
            android:src="@{data.clockedIn ? @drawable/ic_location_on : @drawable/ic_location_off}"/>
        <!--Other view left for brevity-->
 </LinearLayout>
</layout>

build.gradle

代码语言:javascript
运行
复制
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.app.bidunity"
        minSdkVersion 17
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
dataBinding {
    enabled = true
}
compileOptions {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}


}

dependencies {
def arch_version = "2.0.0-rc01"

implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
//material library
implementation 'com.google.android.material:material:1.0.0'
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$arch_version"

testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}

我使用的是Android studio 3.3 Canary 11和gradle 4.10.1,在viewmodel中绑定数据的onclick运行良好,但即使在更改了isClockedIn之后,ImageView也没有改变它的可绘制性。我已经尝试了所有的方法,我甚至调试了一下isClockedIn是否在运行过程中发生了变化,是的,它的值正在发生变化

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-28 03:48:08

你需要让你的isClockedIn variable Observable

因此将其替换为

代码语言:javascript
运行
复制
public boolean isClockedIn = false;

代码语言:javascript
运行
复制
public ObservableBoolean isClockedIn = new ObservableBoolean();

注意:还要确保xml与ViewModel中的变量名相同

参考

编辑:

如果你不想做ObservableField,,那就需要做一些其他的修改。

使用ObservableField,时,您需要使您的可观察扩展BaseObservable,并且在您的livedata中,您将需要在布尔值更改后调用notifyPropertyChanged(BR.isClockedIn);

如果想要使用LiveData作为观察者,首先要为绑定提供一个生命周期

代码语言:javascript
运行
复制
// Specify the current activity as the lifecycle owner (in your activity/fragment).
binding.setLifecycleOwner(this);

在ViewModel中,使用LiveData对象观察更改并对其应用:

代码语言:javascript
运行
复制
MutableLiveData<Boolean> dataToBeObserve = new MutableLiveData<>();
LiveData booleanDataChange = Transformations.map(dataToBeObserve, dataToBeObserve-> dataToBeObserve.value);

现在,对xml使用此booleanDataChange并更改MutableLiveData值以观察数据更改事件。

注意:您可以对更改事件使用相同的LiveData,只需将定义拆分到构造函数调用。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52544038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档