我有一个整数变量,我想在按下按钮时更改它但代码不起作用。据说我应该将bpm设置为最终,但是当我这样做时,我无法增加它!
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);
}
});
答案 0 :(得分: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
也更清晰。