Android MutableLiveData 初始化布尔值

huangapple go评论106阅读模式
英文:

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&lt;Integer&gt; intFoo;

    public MutableLiveData&lt;Integer&gt; intFoo() {
        if (intFoo == null) {
            intFoo = new MutableLiveData&lt;&gt;(42);
        }
        return intFoo;
    }

But, for Boolean? (tried Boolean.FALSE too)

    // Create a LiveData with a Boolean
    private MutableLiveData&lt;Boolean&gt; boolFoo;

    public MutableLiveData&lt;Boolean&gt; boolFoo() {
        if (boolFoo == null) {
            boolFoo = new MutableLiveData&lt;&gt;(false);    &lt;---- &quot;Expected 0 arguments but found 1&quot;
            // since above did not work changed to:
            // boolFoo = new MutableLiveData&lt;&gt;();
            // 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&lt;Boolean&gt;();
 boolFoo.setValue(Boolean.valueOf(false));

huangapple
  • 本文由 发表于 2020年7月22日 19:05:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63032759.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定