Search code examples
javaandroidbooleanonclicklistener

How to set a boolean true again in Android?


The boolean isChecked is declared first time true, than i set in the OnClickListener to false. What i neeed, is to set boolean isChecked again to true in the next OnClickListener. I know that are not in the same scope but how can i do that? This is my code:

answer[j].setOnClickListener(new View.OnClickListener() {
    private boolean isChecked = true;

    @Override
    public void onClick(View v) {
        RadioButton checkedRadioButton = ((RadioButton) v);
        if (isChecked) {
        if (checkedRadioButton.isChecked()) {
            score++;
            isChecked = false;
        }
        }
    }
});

resetButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        isChecked = true;
        score = 0;
    }
});

Thanks!


Solution

  • You just need to declare your boolean outside of the onclick listeners scope. It will then become more accessbile and you can do whatever you need with it. Declare it before your onCreate so it has global access in this class.

    Example

    public class MainActivity extends AppCompatActivity {
    Button btn, btn2;
    boolean isValid;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button);
        btn2 = (Button) findViewById(R.id.button2);
        isValid = true;
    
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isValid = true;
            }
        });
    
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isValid = false;
            }
        });
    
      }
    }
    

    EDIT V2

    I took a look at the code you posted again and from what I can tell your logic is saying if isValid is true (you have if(isValid)) then go into your logic. Well to start you are actually declaring the value as false. So in your code say to being isValid = true; What is happening is your logic is saying the boolean isn't true so don't execute the code.

    Edit V3

    Alright I took a look again at all of your code and I can see what is happening. Since the variable is global now it isn't executing a second time once we declare it as false because it never gets a chance to be reassigned to true again. To be honest I don't see the purpose of this variable. It isn't doing anything other than just being there haha. However if you want to have the variable you should just remove the line isChecked = false; As I said I honestly see no purpose for it in your code.