0

我有一个整数变量,我想在按下按钮但代码不起作用时更改它。是说我应该将 bpm 设置为 final 但是当我这样做时我不能增加它!

Java代码:

super.onCreate(savedInstanceState);
int bpm;
setContentView(R.layout.activity_metronome);
final Button plus = (Button) findViewById(R.id.tempop);
final Button minus = (Button) findViewById(R.id.tempom);
final Button confirm_tempo = (Button) findViewById(R.id.confirmtempo);
final TextView curbpm = (TextView) findViewById(R.id.curbpm);
bpm=60;
curbpm.setText("" + bpm);

plus.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        bpm++;
        curbpm.setText(""+bpm);
    }
});
4

1 回答 1

4

使其具有类范围这意味着将其从方法中取出。

int bpm;
@Override
protected void onCreate (Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_metronome);
  final Button plus = (Button) findViewById(R.id.tempop);
  final Button minus = (Button) findViewById(R.id.tempom);
  final Button confirm_tempo = (Button) findViewById(R.id.confirmtempo);
  final TextView curbpm = (TextView) findViewById(R.id.curbpm);
  bpm=60;
  curbpm.setText("" + bpm);

  plus.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
      bpm++;
      curbpm.setText(""+bpm);
    }
  });
}

使用它也更清洁,String.valueOf (bpm)而不是""+bpm.

于 2013-03-13T21:39:28.707 回答