Я пытаюсь создать RadioGroup
в макете Android, где дочерние RadioButton
растянуты, чтобы равномерно заполнить всю ширина RadioGroup
. Однако я столкнулся с неожиданным поведением при попытке сделать это с помощью RadioButton
, которые были добавлены программно из кода. Сначала немного предыстории ...
Я начал с простого макета, основанного на RelativeLayout
, который содержит большой TextView
и RadioGroup
внизу.
main.xml файл макета выглядит следующим образом:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView android:text="Some text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentTop="true"
android:layout_above="@+id/radio_group"
android:gravity="center"
android:background="@android:color/holo_green_dark"
/>
<RadioGroup android:id="@+id/radio_group"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:background="@android:color/holo_blue_dark">
<RadioButton android:text="Option 1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:background="@android:color/darker_gray"
android:button="@android:color/transparent"
android:padding="10dp"
android:gravity="center"
android:layout_margin="2dp"/>
<RadioButton android:text="Option 2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:background="@android:color/darker_gray"
android:button="@android:color/transparent"
android:padding="10dp"
android:gravity="center"
android:layout_margin="2dp"/>
</RadioGroup>
</RelativeLayout>
который создает следующий макет во время выполнения:
Вы можете видеть, что использование android: layout_width = "wrap_content"
и android: layout_weight = "1"
в обоих RadioButton
s растягивает их, чтобы равномерно заполнить половину охватывающей RadioGroup
каждой. Все идет нормально.
Однако у меня есть требование - динамически создавать RadioButton
в этом макете во время выполнения на основе бизнес-логики, а не всегда использовать два статически включенных в макет - иногда мне могут понадобиться две кнопки, иногда четыре и т. д.
Чтобы реализовать это, я удалил RadioButton
из моего макета main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView android:text="Some text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentTop="true"
android:layout_above="@+id/radio_group"
android:gravity="center"
android:background="@android:color/holo_green_dark"
/>
<RadioGroup android:id="@+id/radio_group"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:background="@android:color/holo_blue_dark"/>
</RelativeLayout>
... и создал отдельный макет _radio_button.xml_ для моего RadioButton
:
<?xml version="1.0" encoding="utf-8"?>
<RadioButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight="1"
android:background="@android:color/darker_gray"
android:button="@android:color/transparent"
android:gravity="center"
android:padding="10dp" />
В моем упражнении я теперь программно добавляю RadioButton
:
public class TestRadioActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create an inflater to inflate our buttons
LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Create the layout params for our buttons
LinearLayout.LayoutParams layoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f);
RadioGroup group = (RadioGroup) findViewById(R.id.radio_group);
// Add button one
RadioButton button = (RadioButton) inflater.inflate(R.layout.radio_button, null);
button.setText("Option 1");
group.addView(button, layoutParams);
// Add button two
button = (RadioButton) inflater.inflate(R.layout.radio_button, null);
button.setText("Option 2");
group.addView(button, layoutParams);
}
}
Обратите внимание, как файл _radio_button.xml_ и действие укажите ширину макета WRAP_CONTENT и вес макета 1 для равномерного распределения кнопок, как в исходном main.xml .
Однако макет, кажется, визуализируется без учета веса макета с кнопками, расположенными встык слева от радиогруппы:
Как было предложено в другом месте, я также попытался установить ширину RadioButton
s на 0 в LayoutParams
(очевидно, это может привести к несколько иной интерпретации веса макета), но это приводит к тому, что RadioButton
s даже не отображается:
Может ли кто-нибудь посоветовать, как получить RadioButton
, чтобы равномерно заполнить всю ширину содержащей RadioGroup
при программном добавлении? Есть ли что-нибудь очевидное, что мне не хватает?