Добавление радиогруппы в настраиваемый диалог

Я пытаюсь установить динамические переключатели в настраиваемый диалог, но не могу добавить его в свой настраиваемый диалог

 final RadioButton[] rb = new RadioButton[5];
 RadioGroup rg = new RadioGroup(this); 
 rg.setOrientation(RadioGroup.VERTICAL);

        // layout params to use when adding each radio button
 LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);

 LinearLayout ll2 = (LinearLayout) findViewById(R.id.linearMain);

 // add 5 radio buttons to the group

 for (int i = 0; i < 5; i++){
      rb[i] = new RadioButton(this);
      String label = "item set" + i;
      rb[i].setText(label);
      rb[i].setId(i);
      rg.addView(rb[i],layoutParams);

      }
 ll2.addView(rg);

--------------------------------------------------------------------

 Context context=LocationActivity.this;
 dialog=new Dialog(context);
 dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

 dialog.setContentView(R.layout.custom_dialog);
     ----------------------------------------------------------------------

 Linearlayout2 is defined in custom_dialog.xml file. I must be doing something wrong but not able to figure it out. Other widgets are getting displayed except radiogroup buttons.

Любой указатель на эту проблему отмечен.

Спасибо! Swz

custom_dialog файл, как показано ниже:

В нем есть 2 виджета textview и объявлена ​​радиогруппа. Я могу успешно добавить тот же макет на экран активности, но не в настраиваемый диалог.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linlayoutBase"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/TextView03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="5dip"
            android:text="Longitute: "
            android:textSize="20dip" >
        </TextView>

        <TextView
            android:id="@+id/TextView04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="unknown"
            android:textSize="20dip" >
        </TextView>
    </LinearLayout>

    <LinearLayout
          android:id="@+id/linearMain"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">

    <RadioGroup
          android:id="@+id/radiogroup"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
    >
    </RadioGroup>

    </LinearLayout>
</LinearLayout>

person swz    schedule 20.11.2012    source источник
comment
Можете ли вы добавить R.layout.custom_dialog файл?   -  person user    schedule 20.11.2012
comment
Вы получаете сообщение об ошибке или они просто не появляются? Кроме того, я вижу, вы говорите, что Linearlayout2 находится в custom_dialog макете, но вы вызываете id linearDialog   -  person jnthnjns    schedule 20.11.2012
comment
В этом XML нет LinearLayout с идентификатором @+id/linearDialog ... Вы получаете NullPointerException?   -  person Sam    schedule 20.11.2012
comment
Приносим извинения за опечатку, LinearLayout II2 является linearMain. Нет, радиокнопки просто не отображаются в настраиваемом диалоговом окне.   -  person swz    schedule 20.11.2012
comment
Я получаю исключение null pointerexception, если пытаюсь объявить радиогруппу как RadioGroup rg = (RadioGroup) findViewById (R.id.radiogroup);   -  person swz    schedule 20.11.2012
comment
Отбросьте эту строку: xmlns:android="http://schemas.android.com/apk/res/android" из своего RadioGroup в xml, не думайте, что это поможет, но вам это не нужно.   -  person jnthnjns    schedule 21.11.2012


Ответы (1)


Глядя на опубликованный вами XML, попробуйте следующее:

Context context=LocationActivity.this;
dialog=new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

View view = LayoutInflater.fromContext(context).inflate(R.layout.custom_dialog, null, false);
RadioGroup rg = (RadioGroup) view.findViewById(R.id.radiogroup);
RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);

 // add 5 radio buttons to the group
RadioButton rb;
for (int i = 0; i < 5; i++){
    rb = new RadioButton(context);
    rb.setText("item set" + i);
    rb.setId(i);
    rg.addView(rb, layoutParams);
}

dialog.setContentView(view);

Я не видел, как вы меняли макет диалогового окна. Итак, я раздул макет, добавил RadioButtons, а затем передал готовый макет dialog.

Кроме того, поскольку linearMain имеет только один дочерний элемент, вы можете удалить этот LinearLayout и просто использовать radioGroup.

person Sam    schedule 20.11.2012
comment
Вы можете найти RadioGroup в представлении, чтобы найти его. - person user; 21.11.2012
comment
Да, мне не нужно создавать вторую RadioGroup в макете, но по некоторым причинам первая давала исключение с нулевым указателем. Я пробовал это решение, но оно у меня не работает. Спасибо! - person swz; 21.11.2012
comment
Я имею в виду, что сейчас я не получаю исключения, но в диалоговом окне отображаются только первые два текстовых виджета. - person swz; 21.11.2012
comment
@Luksprog Спасибо, всегда помогает иметь лишние глаза. - person Sam; 21.11.2012
comment
Спасибо, сработало. боролся с этим последние 2 часа. - person swz; 21.11.2012