我有以下问题。我有3个用于更改背景颜色的按钮(分别为蓝色,红色和绿色),还有5个单选按钮,单击它们将播放声音。背景颜色更改按钮和声音单选按钮都可以完全独立地正常工作。将它们放到一个屏幕上后,一旦选择背景颜色更改按钮之一,应用程序就会崩溃。问题出在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);
}
}
最佳答案
听起来您的onClick()
会因按下按钮而被触发...在这种情况下,View v
并不是RadioButton
而是按钮。
在这种情况下,您的logcat(应始终包括在此处)将显示ClassCastException。
将第二部分包装(处理声音)
if( v instanceof RadioButton ) {
... your code here
}
你应该没事的
关于android - Android:更改背景颜色后,声音应用崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15203801/