代码之家  ›  专栏  ›  技术社区  ›  Sanjeev

当与数据绑定一起使用时,LiveData不会向UI通知更改

  •  -1
  • Sanjeev  · 技术社区  · 8 年前

    LiveData 实时数据 正在更改它不反映UI中的更改。

    主视图模型.java

    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
    }
    

    主活动.java

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

    活动\u main.xml

    <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>
    

    构建.gradle

    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'
    }
    

    我正在使用 具有 渐变4.10.1 和 onclick isClockedIn ImageView 是不会变的,它是可画的。我什么都试过了,我甚至调试过 是的,它的价值在变化

    2 回复  |  直到 8 年前
        1
  •  9
  •   Jeel Vankhede    8 年前

    你需要让你的 isClockedIn 可观测场

    public boolean isClockedIn = false;
    

    到

    public ObservableBoolean isClockedIn = new ObservableBoolean();
    

    视图模型

    here

    编辑:

    如果你不想 可观测场 ,然后需要一些其他的更改。

    纵然 可观测场 ,您需要使您的可观察扩展 BaseObservable 在你的 实时数据 你需要打电话 notifyPropertyChanged(BR.isClockedIn); 布尔值更改后。


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

    // Specify the current activity as the lifecycle owner (in your activity/fragment).
    binding.setLifecycleOwner(this);
    

    在ViewModel中,获取LiveData对象以观察更改并应用 Transformation 在上面:

    MutableLiveData<Boolean> dataToBeObserve = new MutableLiveData<>();
    LiveData booleanDataChange = Transformations.map(dataToBeObserve, dataToBeObserve-> dataToBeObserve.value);
    

    现在,用这个 booleanDataChange 并更改MutableLiveData值以观察数据更改事件。