英文:
Android MutableLiveData initialization for Boolean
问题
我可以为整数初始化Android的MutableLiveData如下:
// 创建一个带有整数的LiveData
private MutableLiveData<Integer> intFoo;
public MutableLiveData<Integer> intFoo() {
if (intFoo == null) {
intFoo = new MutableLiveData<>(42);
}
return intFoo;
}
但是,对于布尔值呢?(尝试了Boolean.FALSE也不行)
// 创建一个带有布尔值的LiveData
private MutableLiveData<Boolean> boolFoo;
public MutableLiveData<Boolean> boolFoo() {
if (boolFoo == null) {
boolFoo = new MutableLiveData<>(); // <---- "Expected 0 arguments but found 1"
// 由于上面的方法不起作用,改成了以下方式:
// boolFoo = new MutableLiveData<>();
// boolFoo.setValue(false);
}
return boolFoo;
}
英文:
I'm able to initialize Android MutableLiveData for Integer as follows:
// Create a LiveData with an Integer
private MutableLiveData<Integer> intFoo;
public MutableLiveData<Integer> intFoo() {
if (intFoo == null) {
intFoo = new MutableLiveData<>(42);
}
return intFoo;
}
But, for Boolean? (tried Boolean.FALSE too)
// Create a LiveData with a Boolean
private MutableLiveData<Boolean> boolFoo;
public MutableLiveData<Boolean> boolFoo() {
if (boolFoo == null) {
boolFoo = new MutableLiveData<>(false); <---- "Expected 0 arguments but found 1"
// since above did not work changed to:
// boolFoo = new MutableLiveData<>();
// boolFoo.setValue(false);
}
return boolFoo;
}
答案1
得分: 1
我检查了MutableLiveData的源代码,并发现MutableLiveData的构造函数已被删除,这意味着您只能使用默认构造函数。因此,要进行初始化,您可以尝试创建一个空的MutableLiveData,然后使用setValue方法设置MutableLiveData的初始值。
boolFoo = new MutableLiveData<Boolean>();
boolFoo.setValue(Boolean.valueOf(false));
英文:
I checked the source code for MutableliveData and found that the constructor for MutableLiveData has been removed, meaning you can only use the default constructor. Therefore to initialise, you can try creating an empty MutableLiveData of your type and use the setValue method to set the initial value of the MutableLiveData.
boolFoo = new MutableLiveData<Boolean>();
boolFoo.setValue(Boolean.valueOf(false));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论