我有一个ImageView作为按钮。如果我点击它,播放声音并切换到另一个活动,我想要它。单独它完美地工作,但我不能混合它们,它只能播放声音或切换活动。 活动开关代码:
public void imagebutton (View v) {
Intent startNewActivity = new Intent(this, NewActivity.class);
startActivity(startNewActivity);
}
声音代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer sound = MediaPlayer.create(this, R.raw.clicksound);
ImageView click = (ImageView) findViewById(R.id.imagebutton);
click.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v){
sound.start();
}
}
);
感谢。
答案 0 :(得分:1)
试试这个,
click.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v){
sound.start();
Intent startNewActivity = new Intent(MainActivity.this, NewActivity.class);
startActivity(startNewActivity);
}
}
);
还要检查manifest.xml中的.NewActivity
答案 1 :(得分:0)
使用您的代码启动sound.start();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer sound = MediaPlayer.create(this, R.raw.clicksound);
ImageView click = (ImageView) findViewById(R.id.imagebutton);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v){
sound.start();
Intent startNewActivity = new Intent(this, NewActivity.class);
startActivity(startNewActivity);
}
}
);
答案 2 :(得分:0)
您可以在开始新活动之前实现AsyncTask以重现您的声音。
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
MediaPlayer player = MediaPlayer.create(this, R.raw.clicksound);
player.setLooping(true); // Set looping if you want
player.setVolume(100,100); // Set Volume if you want
player.start();
return null;
}
}
并使用如下:BackgroundSound.execute();在开始新活动之前。
答案 3 :(得分:0)
您可以使用setOnCompletionListener确保声音结束然后开始新活动:
final MediaPlayer sound = MediaPlayer.create(this, R.raw.clicksound);
sound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Intent startNewActivity = new Intent(this, NewActivity.class);
startActivity(startNewActivity);
}
});
ImageView click = (ImageView) findViewById(R.id.imagebutton);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v){
sound.start();
}
}