简体   繁体   中英

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. I have set the value to be false and true within the if statement of the fade method. 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. 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. 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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