I'm new at programming android apps. How can I change a variable (bool) inside a button-method (or any method)
Here is just an example:
package com.example.test1;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.renderscript.Sampler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button btn1,btn2;
Boolean player1is = true;
TextView controllview;
TextView controllview2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1= findViewById(R.id.button1);
btn2 = findViewById(R.id.button2);
controllview=findViewById(R.id.controll1);
controllview2=findViewById(R.id.controll2);
if(player1is){
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
player1is = false;
controllview.setText(String.valueOf(player1is));
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
});
}else {
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
player1is = true;
controllview.setText(String.valueOf(player1is));
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
});
}
controllview2.setText(String.valueOf(player1is));
}
}
If I run this code, controllview changes but controllview2, which shows the global value of player1is, does not change.
I also tried to change the value in a separate method like:
public void changebool(Boolean c) {
player1is= c;
}
then call it from the onclick-method with the desired value, but it had the same effect.
I know, that I am missing a very basic point here but the examples I found were not satisfying (or I searched the wrong way).
What I plan to do is, that every "player" (in an already working, more complex app - apart from this minor issue) can push the button alternately.
Also tried to use a switch or write and read values to a textview in the corresponding XML.
I want that the two buttons will work alternately. I put it in another way:
- Until Button1 is not pressed, Button2 should not work but a klick on Button1 activates Button2. (And of cause the other way) Its for determine turns in another app.
Use
java.util.concurrent.atomic.AtomicBooleanmay solve this problem