public void one() {
first = MediaPlayer.create(this, R.raw.dokey);
first.start();
first.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
play.release();
}
});
}
@Override
public void onClick(View v) {
if(v==key1){ //key1 is the button
one();
}
//and so on...
}
}
答案 0 :(得分:1)
在不了解太多代码的情况下,我认为您可以提取clicklistener并执行以下操作:
private class OnKeyClickListener implements View.OnClickListener {
private MediaPlayer mMediaPlayer;
public OnKeyClickListener(MediaPlayer mediaPlayer) {
mMediaPlayer = mediaPlayer;
}
@Override public void onClick(View view) {
/// do the thing
}
}
然后将其添加到键中:
MediaPlayer mediaPlayer1 = new MediaPlayer(); // mediaplayer for key 1
key1.setOnClickListener(new OnKeyClickListener(mediaPlayer1));
MediaPlayer mediaPlayer2 = new MediaPlayer(); // mediaplayer for key 2
key2.setOnClickListener(new OnKeyClickListener(mediaPlayer2));
编辑1: 或者,您可以将mediaplayer添加为View的标记。
key1.setTag(mediaplayer1);
然后在onClick中获取点击的视图标记并将其转换为媒体播放器。
onClick(View v) {
Mediaplayer mediaplayer = (MediaPlayer) v.getTag();
}