在我的 JumbledWords 游戏应用程序中,我提供了打开和关闭声音的选项。问题是我无法做到这一点。我已经为其编写了代码,但它不起作用。
SplashScreen.java
RadioButton rbSoundOn, rbSoundOff;
JumbledWords jw = new JumbledWords();
@Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
//set the full screen view of the activity
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_screen);
rbSoundOn = (RadioButton)findViewById(R.id.optSoundOn);
rbSoundOff = (RadioButton)findViewById(R.id.optSoundOff);
if(rbSoundOn.isChecked() == true)
{
jw.setSoundOn(true);
}
else
{
jw.setSoundOn(false);
}}
JumbledWords.java
static boolean soundOn;
public void setSoundOn(boolean soundOn)
{
this.soundOn = soundOn;
}
public boolean isSoundOn()
{
return soundOn;
}
public void checkWord()
{
if(abcd.equalsIgnoreCase(etGuessedWord.getText().toString()))
{
WordLibrary.setMyInt(WordLibrary.getMyInt() + 10);
tvScore.setText(String.valueOf(WordLibrary.getMyInt()));
if(soundOn == true)
{
mp = MediaPlayer.create(this, R.raw.clap);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
mp.release();
}
});
}
}
else
{
if(soundOn == true)
{
mp = MediaPlayer.create(this, R.raw.oop);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
mp.release();
}
});
}
}
}
我的问题是,如果我使用“关闭”选项,我的声音就会播放,在这种情况下一定不会发生这种情况。请帮助我。
最佳答案
您实际上并没有处理对单选按钮的更改。
您需要定义RadioGroup控件来包装您的RadioButton控件,并定义单选按钮的“组”;然后在 RadioGroup 上调用 setOnCheckedChangeListener()
来定义一个监听器,当状态更改时将调用该监听器。您需要在此监听器中检查各个按钮的状态并调用 jw.setSoundOn();
,而不是在 onCreate()
方法中执行此操作:
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
//set the full screen view of the activity
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_screen);
RadioGroup group = (RadioGroup)findViewById( R.id.optSoundGroup );
final RadioButton rbSoundOn = (RadioButton)findViewById(R.id.optSoundOn);
final RadioButton rbSoundOff = (RadioButton)findViewById(R.id.optSoundOff);
group.setOnCheckedChangeListener( new OnCheckedChangeListener() {
@Override
void onCheckedChanged(RadioGroup group, int checkedId)
{
if(rbSoundOn.isChecked() == true)
{
jw.setSoundOn(true);
}
else
{
jw.setSoundOn(false);
}
}
} );
}
关于android - 如何在android中以编程方式设置声音打开和关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6341726/