我有以下问题。我有 3 个按钮用于更改背景颜色(分别为蓝色、红色和绿色),还有 5 个单选按钮,单击时会播放声音。背景颜色更改按钮和声音单选按钮都可以独立工作。As soon as I put them together on one screen, the application will crash when one of the background color change button is selected. 问题在于 RadioButton 行,特别是在这里:
RadioButton rb = (RadioButton) v;
我不知道该怎么做才能解决这个错误。有人可以帮助我吗?
这是 onClick 方法的代码:
public void onClick(View v) {
RelativeLayout rl = (RelativeLayout) findViewById(R.id.RelativeLayout1);
switch (v.getId())
{
case R.id.button1:
Toast.makeText(getBaseContext(), "You switched the color to red!" , Toast.LENGTH_SHORT ).show();
rl.setBackgroundColor(Color.RED);
break;
case R.id.button2:
Toast.makeText(getBaseContext(), "You switched the color to green!" , Toast.LENGTH_SHORT ).show();
rl.setBackgroundColor(Color.GREEN);
break;
case R.id.button3:
Toast.makeText(getBaseContext(), "You switched the color to blue" , Toast.LENGTH_SHORT ).show();
rl.setBackgroundColor(Color.BLUE);
break;
case R.id.cancel:
Toast.makeText(getBaseContext(), "This application will be closed!" , Toast.LENGTH_SHORT ).show();
finish();
break;
}
//Perform action on clicks
RadioButton rb = (RadioButton) v;
//get the user sound settings
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
//get current volume
float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//get maximum volume
float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
//is the sound loaded already?
if(loaded) {
//play the sound
if (rb.getText().toString().equals("Clong!"))
gameAudio.play(soundIDs[0], volume, volume, 1, 0, 1f);
else if (rb.getText().toString().equals("Hammering!"))
gameAudio.play(soundIDs[1], volume, volume, 1, 0, 1f);
else if (rb.getText().toString().equals("Chainsaw Attack!"))
gameAudio.play(soundIDs[2], volume, volume, 1, 0, 1f);
else if (rb.getText().toString().equals("Smoke alarm!"))
gameAudio.play(soundIDs[3], volume, volume, 1, 0, 1f);
else if (rb.getText().toString().equals("Sharp the knife!"))
gameAudio.play(soundIDs[4], volume, volume, 1, 0, 1f);
}
}