在Android中若把RadioGroup放置在自定义对话框中而且对RadioGroup做出监听就会出现空指针错误,
这是由于RadioGroup找不到自定义对话框的xml中的id造成的,若添加如下代码可以解决问题
- RelativeLayout dialayout=(RelativeLayout)getLayoutInflater().inflate(R.layout.dialog, null);
然后findViewById()方法要加上变量
- RadioGroup rg=(RadioGroup)dialayout.findViewById(R.id.rg);
其实不只是RadioGroup放置在自定义对话框中会出现问题,其他控件也会出现这个问题,都可以用上述方法解决
下面附赠一个方法,可以创建带有确定和取消按钮的对话框,以及对话框中对RadioGroup中的radioButton子元素进行判断
方法ple():
- public void ple()
- {
- int w_radioButton=null;
- RelativeLayout dialayout=(RelativeLayout)getLayoutInflater().inflate(R.layout.dialog, null);
- rg=(RadioGroup)dialayout.findViewById(R.id.rg);
- rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(RadioGroup arg0, int arg1) {
- // TODO Auto-generated method stub
- if(arg1==R.id.radioButton1){
- w_radioButton=1;
- }else
- {
- if(arg1==R.id.radioButton2){
- w_radioButton=2;
- }else{
- if(arg1==R.id.radioButton3)
- {
- w_radioButton=3;
- }
- else
- {
- if(arg1==R.id.radioButton4)
- {
- w_radioButton=4;
- }
- else
- {
- if(arg1==R.id.radioButton5)
- {
- w_radioButton=5;
- }
- }
- }
- }
- }
- }
- });
- new AlertDialog.Builder(this).setTitle("title").setIcon(R.drawable.time).setView(dialayout)
- .setPositiveButton("确定", new OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog,int which) {
- }
- })
- .setNegativeButton("取消", new OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog,int which) {
- // TODO Auto-generated method stub
- }
- }).create().show();
- }
下面是layout中的dialog.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <RadioGroup
- android:id="@+id/rg"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:orientation="vertical"
- android:layout_alignParentTop="true"
- android:layout_margin="10dp" >
- <RadioButton
- android:id="@+id/radioButton1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text=" 111"
- android:textColor="#cbd5f3" />
- <RadioButton
- android:id="@+id/radioButton2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text=" 222"
- android:textColor="#cbd5f3"/>
- <RadioButton
- android:id="@+id/radioButton3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text=" 333"
- android:textColor="#cbd5f3"/>
- <RadioButton
- android:id="@+id/radioButton4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text=" 444"
- android:textColor="#cbd5f3" />
- <RadioButton
- android:id="@+id/radioButton5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text=" 555"
- android:textColor="#cbd5f3" />
- </RadioGroup>
- </RelativeLayout>