main.xml文件
-----------------------------<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
      <!--RadioGroup 代表组   RadioButton 代表组里面的按钮 -->
    <RadioGroup 
     android:id="@+id/group"
     android:layout_width="wrap_content" 
 android:layout_height="wrap_content">
 
      <RadioButton 
android:text="男" 
android:id="@+id/radioButton1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</RadioButton>

<RadioButton 
android:text="女" 
android:id="@+id/radioButton2" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</RadioButton>

    </RadioGroup>
</LinearLayout>RadioGroupButton.java
-------------------------------------
package test.RadioGroupButton;import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;public class RadioGroupButton extends Activity {
/** Called when the activity is first created. */
private RadioGroup rgp = null;
private RadioButton rb1 = null;
private RadioButton rb2 = null; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rgp = (RadioGroup) findViewById(R.id.group);
rb1 = (RadioButton) findViewById(R.id.radioButton1);
rb1 = (RadioButton) findViewById(R.id.radioButton2); rgp.setOnCheckedChangeListener(groupCheck);
} private RadioGroup.OnCheckedChangeListener groupCheck = new RadioGroup.OnCheckedChangeListener() { @Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (rb1.getId() == checkedId) {
System.out.println("男");
Toast.makeText(RadioGroupButton.this, "男", Toast.LENGTH_SHORT)
.show();
} else if (rb2.getId() == checkedId) {
System.out.println("女");
Toast.makeText(RadioGroupButton.this, "女", Toast.LENGTH_SHORT)
.show();
}
}
};
}
-----------------------------------------
为什么我的RdioGroup  一点击 男的点选按钮就报错 点击女的时候 不报错

解决方案 »

  1.   


    rgp = (RadioGroup) findViewById(R.id.group);
    rb1 = (RadioButton) findViewById(R.id.radioButton1);
    rb1 = (RadioButton) findViewById(R.id.radioButton2);这里看到了么?
    改回来吧。
      

  2.   

    #1 正确,需要修改rb1 = (RadioButton) findViewById(R.id.radioButton2);为rb2 = (RadioButton) findViewById(R.id.radioButton2);
      

  3.   

    错误太明显了哈这种radiobutton命名的时候最好直接用male跟female这些来表示,不要还继续用button1,button2简单明了