[英]Media Player won't play the sound in button click method
I have 3 buttons and they are supposed to play 3 different sounds. 我有3个按钮,他们应该播放3种不同的声音。 When I used 3 separate onclicks methods in oncreate method it worked properly, but I wanted to clean the code a little, so I implemented OnClickListener to acvtivity and moved the onclick methods down.
当我在oncreate方法中使用3个单独的onclicks方法时它工作正常,但我想稍微清理一下代码,所以我将OnClickListener实现为acvtivity并将onclick方法向下移动。 But now, media players don't play the sounds.
但现在,媒体播放器不播放声音。 How can I make sure media players work?
我怎样才能确保媒体播放器有效?
public class Play extends Activity implements OnClickListener {
MediaPlayer mpPlay1,mpPlay2,mpPlay3;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
Button bPlay1 = (Button) findViewById(R.id.button1);
Button bPlay2 = (Button) findViewById(R.id.button2);
Button bPlay3 = (Button) findViewById(R.id.button3);
int resIdPlay1 = getResources().getIdentifier("play1", "raw", getPackageName());
int resIdPlay2 = getResources().getIdentifier("play2", "raw", getPackageName());
int resIdPlay3 = getResources().getIdentifier("play3", "raw", getPackageName());
mpPlay1 = MediaPlayer.create(this, resIdPlay1);
mpPlay2 = MediaPlayer.create(this, resIdPlay2);
mpPlay3 = MediaPlayer.create(this, resIdPlay3);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
mpPlay1.start();
break;
case R.id.button2:
mpPlay2.start();
break;
case R.id.button3:
mpPlay3.start();
break;
}
}
}
You haven't implemented the listener on the Buttons
yet, or at least haven't shown it. 您还没有在
Buttons
上实现监听器,或者至少没有显示它。 You should have something like 你应该有类似的东西
Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(this);
inside your onCreate()
after setContentView()
. 在
setContentView()
之后的onCreate()
内部。 You would need this for each Button
. 每个
Button
都需要这个。
Since you are trying to clean up your code and make it more condensed, you can set the onClick()
in your xml. 由于您正在尝试清理代码并使其更加精简,因此可以在xml中设置
onClick()
。
I have explained it in this answer and this one 我在这个答案中解释了这 一点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.