如何在按下按钮时更改变量的值 (Android Studio)

How to change the value of a variable on button press (Android Studio)

我正在尝试制作我的第一个 Android 应用程序,但遇到了一个我不知道如何修复的错误。 我想在按下图像按钮时更改名为 buttonPressed 的变量的值,这是我目前的代码: boolean buttonPressed = false;

ImageButton button_a=(ImageButton)findViewById(R.id.blue_a_button);

//a function to play the audio when button_a is pressed
button_a.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        player=MediaPlayer.create(GameActivity.this,R.raw.a);

        player.start();

        buttonPressed = true;

    }
});

但是,当我将其输入 Android Studio 时出现错误:"variable "buttonPressed" is acccessed from inner class, needs to be declared final"

如果我将变量设置为 final,则无法更改该值。我该怎么办?

干杯:)

只需将您的变量声明为:

  public  class <Your Class Name> extends Activity{

       private boolean buttonPressed;

如果您想在按下按钮时访问该变量,则应将其声明为 class 变量

public class MainActivity extends Activity {

    Boolean buttonPressed = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {

    //-->>>>> If you will declare the variable here, then it has to be final..

    final Button button_a = (Button) findViewById(R.id.button_a);

    //a function to play the audio when button_a is pressed
    button_a.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            player=MediaPlayer.create(GameActivity.this,R.raw.a);
            player.start();
            buttonPressed = true;
        }
    });
    }
}