Android 变量是在内部类中访问的,需要声明为final
我试图让一个按钮将其值与其他变量进行比较。在onClick方法中,我得到一个错误,表示变量是在内部类中访问的,需要声明为final。问题是这个变量应该被更改,所以我不能使它成为最终变量。我怎样才能解决这个问题?这是我的密码:Android 变量是在内部类中访问的,需要声明为final,android,button,onclick,Android,Button,Onclick,我试图让一个按钮将其值与其他变量进行比较。在onClick方法中,我得到一个错误,表示变量是在内部类中访问的,需要声明为final。问题是这个变量应该被更改,所以我不能使它成为最终变量。我怎样才能解决这个问题?这是我的密码: import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Text
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
最终版
:
@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());
...
}
});
}
buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Button btn = (Button)v;
int answerGiven = Integer.parseInt("" + btn.getText());
...
}
});