我正在使用Android Studio 3.1.3。
我的应用程序包含八个按钮。我试图将多个按钮作为onClick方法的参数传递
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
pauseAudio(audioTwo, audioThree, audioFour, audioFive, audioSix, audioSeven, audioEight);
mediaPlayer = MediaPlayer.create(this,R.raw.birds);
mediaPlayer.start();
break;
要暂停Audio方法,
public void pauseAudio(View view, Button audioOne, Button audioTwo, Button audioThree, Button audioFour, Button audioFive, Button audioSix, Button audioSeven, Button audioEight){
if(audioOne.isEnabled()
|| audioTwo.isEnabled()
|| audioThree.isEnabled()
|| audioFour.isEnabled()
|| audioFive.isEnabled()
|| audioSix.isEnabled()
|| audioSeven.isEnabled()
|| audioEight.isEnabled()){
if(mediaPlayer.isPlaying() && mediaPlayer!=null){
mediaPlayer.stop();
}
}
}
答案 0 :(得分:2)
要使您的代码更轻松并且希望可以工作,请尝试以下操作:
public void pauseAudio(View... views) {
for(View view : views) {
if(view.isEnabled()) {
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
break;
}
}
}
现在您可以这样称呼它:
pauseAudio(audioOne, audioTwo, audioThree, ...);
编辑:
也许还检查视图是否未初始化:
if(view != null && view.isEnabled())
编辑2:
我很高兴听到它起作用:)这是一个更好的解释:
public void pauseAudio(View... views) { //Allow a dynamic initialization of an array of Views
for(View view : views) { //Loop through the array
if(view != null && view.isEnabled()) { //If the current view is not null and enabled
if(mediaPlayer!=null && mediaPlayer.isPlaying()){ //If the MediaPlayer is not null and playing
mediaPlayer.stop(); //Stop the MediaPlayer
}
break; //Break the loop, as we have reached our usecase
}
}
}
答案 1 :(得分:0)
也许如果您在崩溃后发布日志,我们可以为您提供更好的帮助。但我已经看到一个可能崩溃的控件
if (mediaPlayer.isPlaying () && mediaPlayer! = null) {
mediaPlayer.stop ();
}
。您可以先检查mediaPlayer!像这样在mediaPlayer.isPlaying()之前= null:
if (mediaPlayer! = null && mediaPlayer.isPlaying ()) {
mediaPlayer.stop ();
}