简体   繁体   English

Android-从另一个类调用布尔值

[英]Android - Call Boolean Value from Another Class

If I set a value to true in one class, such as 如果我在一个类中将值设置为true,例如

static boolean mIsPremium = true;

I only get the correct value sometimes, as in if I use double equal signs (==) I will always return the true value. 有时我只会得到正确的值,就像使用双等号(==)一样,我将始终返回真实值。

if (firstClass.mIsPremium == true){
    do stuff
} else {
    do other stuff
}

If I only use one equal sign (=) it will return a true value, this happens when I set mIsPremium to false in the first class. 如果我仅使用一个等号(=),它将返回一个true值,这是在第一类中将mIsPremium设置为false时发生的。

if (firstClass.mIsPremium = true){
    do stuff
} else {
    do other stuff
}

I have tried many configurations, using two = signs, using one = sign, including a new boolean in the second class that has its own value dependant upon the first boolean's value... Nothing I do seems to work correctly. 我已经尝试了许多配置,使用两个=符号,使用一个=符号,包括第二个类中的一个新布尔值,该布尔值的值取决于第一个布尔值的值...我似乎没有做任何工作。

How do I call a boolean value from another class and have the value correctly used in the second class. 如何从另一个类调用布尔值,并在第二个类中正确使用该值。 If it's true I want it true in the second class, if its false I want it false in the second class. 如果为真,我希望在第二堂课中为真,如果为假,我希望在第二堂课中为假。

you are confused with the operators . 您对运营商感到困惑。

=

Is assigns the value 被赋值

==

checks for the equality 检查是否相等

if (firstClass.mIsPremium = true){

The above line considering it as a statement and assigns the value true to mIsPremium and proceeding further. 上一行将其视为语句,并将值true分配给mIsPremium并继续进行。

if (firstClass.mIsPremium == true){ 

Checks if the values of two operands are equal or not, if yes then condition becomes true. 检查两个操作数的值是否相等,如果是,则条件为真。

What you do is 你要做的是

if (firstClass.mIsPremium){
    do stuff
} else {
    do other stuff
}

One = sing is an assignment, an assignment in always true. 一个= sing是一个分配,一个分配始终为true。

(a = b) #-> always true, it doesn't matter if a or b are false or true

Two = sing is a comparison, the result depends on what are the values of a and b. 2 = sing是一个比较,结果取决于a和b的值是多少。

(a == b) #-> true if and only if a has the same value of b

Boolean can only have two values as true/false.No need to use == or = 布尔值只能有两个值为true / false的值,无需使用==或=

just use 只是使用

if (firstClass.mIsPremium)     //if mIsPremium is true
{     
    do stuff
} else {
    do other stuff
}

you do not need to use any = signs you can just do 您不需要使用任何=号就可以做到

if(firstClass.mIsPremium) { } // check for premium

or 要么

if(!firstClass.mIsPremium) { } // check for not premium

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM