简体   繁体   English

从未使用分配的布尔值-Java / Android Studio

[英]Boolean value assigned is never used - Java / Android Studio

I don't understand why Android Studio is telling me that the value assigned to isOne is never being used. 我不明白为什么Android Studio告诉我从未使用分配给isOne的值。 I have set the value to be false and true within the if statement of the fade method. 我已将衰落方法的if语句中的值设置为false和true。 When I declare the variable isOne as a member variable instead of a local variable, however, the error is gone and it seems to work perfectly. 但是,当我将变量isOne声明为成员变量而不是局部变量时,该错误消失了,并且似乎可以正常工作。 I'm not sure why that fixed the error....Any thoughts ? 我不确定为什么能解决这个错误。...有什么想法吗?

private ImageView img1;
private ImageView img2;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    img1 = (ImageView) findViewById(R.id.porsche1);
    img2 = (ImageView) findViewById(R.id.porsche2);

    img1.setOnClickListener(this);
    img2.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    fade();
}

public void fade(){
   boolean isOne = true;

    if (isOne) {
        img1.animate().alpha(0).setDuration(2000);
        img2.animate().alpha(1).setDuration(2000);
        isOne = false;
    } else {
        img1.animate().alpha(1).setDuration(2000);
        img2.animate().alpha(0).setDuration(2000);
        isOne = true;
    }

}

} }

Use this way, I hope it will help for you 使用这种方式,希望对您有帮助

boolean isOne = false;   // Use Globally

    public void fade(){

        if (isOne) {
            img1.animate().alpha(0).setDuration(2000);
            img2.animate().alpha(1).setDuration(2000);   
        } else {
            img1.animate().alpha(1).setDuration(2000);
            img2.animate().alpha(0).setDuration(2000);
        }
    }

At the end of both the "if" and "else" blocks, you assign a value to isOne. 在“ if”和“ else”块的末尾,都将一个值分配给isOne。 You never use that value after setting it, so those assignments are unused. 设置它后,您再也不会使用该值,因此这些分配未使用。 Each new invocation redeclares isOne, so that last assignment does not become the next invocation's initial value. 每个新的调用都重新声明isOne,因此最后的分配不会成为下一个调用的初始值。

Fields are harder to analyze, since the last assignment of one invocation would be used as the initial value of the next invocation (assuming there two methods are invoked on the same instance). 字段更难分析,因为一次调用的最后一次分配将用作下一次调用的初始值(假设在同一实例上调用了两种方法)。

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

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