android 单选框如何动态渲染?

androidRadioGroup 是通过 RadioButtonid 来实现单选:

<RadioGroup
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal"
                        >
                            <RadioButton
                                    android:id="@+id/male_radio"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="男"
                                android:checked="true"
                            />
                            <RadioButton
                                    android:id="@+id/female_radio"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:text="女"
                                    android:checked="false"
                            />
                        </RadioGroup>

如果枚举是从服务端获取并且枚举随时可增加、减少,就需要动态渲染,通过编程方式动态往 RadioGroup 新增、减少 RadioButton 是一个方法,但感觉太繁琐了。用 RecyclerView 又会导致 RadioButton 的单选特性无效,需自行维护单选效果。

请问这种业务场景一般怎么实现?

阅读 900
1 个回答
RadioGroup radioGroup = findViewById(R.id.radioGroup);
for (String option : optionsFromServer) {
    RadioButton radioButton = new RadioButton(this);
    radioButton.setText(option);
    radioButton.setId(View.generateViewId());
    radioGroup.addView(radioButton);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题