请问我在让模拟器处理我的代码时遇到问题。我有下面的代码,我希望能够播放声音,当我点击我在模拟器上创建的按钮,但每当我运行代码时,模拟器不弹出,而是媒体播放器弹出,声音播放它自己的。请帮忙。有什么我做错了吗?谢谢你的帮助。
以下是我的代码
public class Sound扩展ActionBarActivity {
MediaPlayer Sound;
private static Button btnsound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
Sound = MediaPlayer.create(this, R.raw.coins);
playsound();
}
public void playSound (View view) {
Sound.start();
}
public void playsound(){
btnsound=(Button) findViewById(R.id.button_sound);
btnsound.setOnClickListener(
new View.OnClickListener(){
@Override
public void onClick (View v){
Sound.start();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sound, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity.xml
<Button
android:layout_width="175dp"
android:layout_height="wrap_content"
android:text="@string/btnsound"
android:onClick="playSound"
android:id="@+id/button_sound"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="154dp" />
答案 0 :(得分:0)
当声音在它自己的声音上播放时,你在onCreate
内部调用方法playsound()
,删除该行并在Button Listener中调用此方法,使它保持这样:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
Sound = MediaPlayer.create(this, R.raw.coins);
btnsound = (Button) findViewById(R.id.button_sound);
btnsound.setOnClickListener(
new View.OnClickListener(){
@Override
public void onClick (View v){
playSound();
}
});
}
public void playSound () {
Sound.start();
}
你的声明和功能有些混乱,请注意。