我有这 3 个类,即 MainActivity、Options 和 Play。当用户单击选项按钮时,用户可以决定是否要播放音频。但默认情况下,尽管用户不会单击选项上的按钮,但仍会播放音频。
我在 StackOverflow 中找到了一些代码,但是如果用户在决定播放音频后决定停止音频,我不知道如何停止音频。(再次进入选项)
这是到目前为止的代码:
MainActivity.class(选项)
public class MainActivity extends Activity {
public MediaPlayer mp = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent a = new Intent(MainActivity.this, Play.class);
startActivity(a);
}
});
}
}
播放.java
public class Play extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
Button back = (Button) findViewById (R.id.button1);
back.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent menu = new Intent (getApplicationContext(), Menu.class);
startActivity(menu);
}
});
MainActivity z = new MainActivity();
MediaPlayer mp = z.mp;
if (mp == null) {
mp = MediaPlayer.create(Play.this, R.raw.math_game);
mp.start();
}
else if (mp.isPlaying()) {
mp.stop();
mp = null;
}
}
}
和主菜单
public class Menu extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
Button play, opt;
play = (Button) findViewById (R.id.play);
opt = (Button) findViewById (R.id.opt);
play.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent play = new Intent (Menu.this, Play.class);
startActivity(play);
}
});
opt.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent play = new Intent (Menu.this, MainActivity.class);
startActivity(play);
}
});
}
}
谢谢 :))