我正在为Android编程一个节拍器并使用一个线程在用户说的节奏中播放声音但不知何故我的setOnClickListener
无法正常工作。单击按钮时,按钮甚至无法单击。我的代码出了什么问题?
startb = (Button) findViewById(R.id.start_but);
stopb = (Button) findViewById(R.id.stop_but);
startb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
running = true;
bpm_val = findViewById(R.id.metr_input);
value = bpm_val.getText().toString();
int beat = Integer.parseInt(value);
Soundplay(beat / 60); //The beats per second
}
});
stopb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
running = false;
}
});
}
public void Soundplay(final long bps) {
startb = (Button) findViewById(R.id.start_but);
stopb = (Button) findViewById(R.id.stop_but);
running = true;
new Thread() {
@Override
public void run() {
super.run();
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.metronome_klack);
int i = 0;
while (running) {
if(i == 1000) {
mp.start();
i = 0;
}
try {
sleep(bps);
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
答案 0 :(得分:0)
您已在代码中初始化按钮两次。 首先是 onCreate()方法,第二次是 Soundplay(最终长bps)方法。您可以从 Soundplay 方法中删除初始化。看起来按钮是在其点击列表器本身上初始化的。我认为这就是问题所在。
public void Soundplay(final long bps) {
//Remove this portion
**startb = (Button) findViewById(R.id.start_but);**
**stopb = (Button) findViewById(R.id.stop_but);**
...
}
希望它有所帮助。