android 监听多个 MutableLiveData 属性变化?

android 监听多个 MutableLiveData 属性变化?

视图代码如下:

<Button 

// ...

android:text="@{vm.getText()}"

/>

java代码如下:

class TestVM extends ViewModel {

private final MutableLiveData<Boolean> isRequest = new MutableLiveData<>();

private final MutableLiveData<Integer> total = new MutableLiveData<>();

public TestVM() {

this.isReqeust.setValue(false);

this.total.setValue(10);

}

public String getText() {

if (this.isRequest.getValue()) {

return "请求中";

}

int total = this.total.getValue();

if (total >= 1000) {

return '999+';

}

return String.valueOf(total);

}

}

上述代码在 isRequesttotal 变化的时候,界面上显示的文本不更新,请问该怎么解决?


回答:

用 MediatorLiveData:

class TestVM extends ViewModel {

private final MutableLiveData<Boolean> isRequest = new MutableLiveData<>();

private final MutableLiveData<Integer> total = new MutableLiveData<>();

public final MediatorLiveData<String> text = new MediatorLiveData<>();

public TestVM() {

this.isRequest.setValue(false);

this.total.setValue(10);

text.addSource(isRequest, value -> text.setValue(getText()));

text.addSource(total, value -> text.setValue(getText()));

}

private String getText() {

if (this.isRequest.getValue()) {

return "请求中";

}

int total = this.total.getValue();

if (total >= 1000) {

return "999+";

}

return String.valueOf(total);

}

}

或者

TestVM viewModel = new ViewModelProvider(this).get(TestVM.class);

viewModel.isRequest.observe(this, new Observer<Boolean>() {

@Override

public void onChanged(Boolean isRequest) {

updateButtonText();

}

});

viewModel.total.observe(this, new Observer<Integer>() {

@Override

public void onChanged(Integer total) {

updateButtonText();

}

});

private void updateButtonText() {

String text = viewModel.getText();

myButton.setText(text); // 假设myButton是你的Button对象

}

以上是 android 监听多个 MutableLiveData 属性变化? 的全部内容, 来源链接: utcz.com/p/945322.html

回到顶部