变量在内部类中访问,需要声明为 final



我正在尝试让一个按钮将其值与其他变量进行比较。在 onClick 方法中,我收到一个错误,指出变量在内部类中被访问,需要声明为 final。问题是变量应该被改变,所以我不能让它成为最终的。我该如何解决这个问题?这是我的代码:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class GameActivity extends Activity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);    
        int partA = 9;
        int partB = 9;
        int correctAnswer = partA * partB;
        int wrongAnswer1 = correctAnswer++;
        int wrongAnswer2 = correctAnswer--;
        TextView textObjectA = (TextView)findViewById(R.id.textPartA);
        TextView textObjectB = (TextView)findViewById(R.id.textPartB);
        Button buttonObjectChoice1 = (Button)findViewById(R.id.buttonChoice1);
        Button buttonObjectChoice2 = (Button)findViewById(R.id.buttonChoice2);
        Button buttonObjectChoice3 = (Button)findViewById(R.id.buttonChoice3);

        buttonObjectChoice1.setText("" + correctAnswer);
        buttonObjectChoice2.setText("" + wrongAnswer1);
        buttonObjectChoice3.setText("" + wrongAnswer2);    
        buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
                if(correctAnswer==answerGiven)  {
                }
            }
        });
        buttonObjectChoice1.setOnClickListener(this);
        buttonObjectChoice1.setOnClickListener(this);

    }
    public void onClick(View view)  {}
}

两种方法:

  1. 制作buttonObjectChoice1 final

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        final Button buttonObjectChoice1 =(Button)findViewById(R.id.buttonChoice1);
        ...
        buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               int answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
                ...
            }
        });
    }
    
  2. 在运行时转换视图:

    buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Button btn = (Button)v;
            int answerGiven = Integer.parseInt("" + btn.getText());
            ...
         }
    });
    

方法2的优点是,它将减少编译器生成访问器方法来访问buttonObjectChoice1对象的工作量。

尝试将变量声明为类的私有字段,并在方法中相应地更新它。

最新更新