【发布时间】:2012-09-11 15:30:53
【问题描述】:
我正在 Android 应用中构建一个表单。
表单有几个字段,其中两个组件是 RadioGroups。包括其按钮的第一组完全在活动的布局文件中定义。对于第二组,只有 RadioGroup 元素在布局文件中定义,其中 RadioButtons 在运行时被添加到组中。
如下图所示,我遇到了一些样式问题。第二组中的单选按钮看起来与第一组中的按钮不同。第二组的按钮图像和文本颜色不同。除了按钮的方向之外,两个 RadioGroup 都配置有相同的属性。当我直接在布局文件中添加第二组的按钮时,它们的外观与第一组相同。
布局文件。
<RadioGroup
android:id="@+id/radio_gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radio_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/checkout_gender_male" />
<RadioButton
android:id="@+id/radio_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/checkout_gender_female" />
</RadioGroup>
...
<RadioGroup
android:id="@+id/radio_payment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp" >
</RadioGroup>
添加单选按钮的代码。
RadioGroup paymentGroup = (RadioGroup) findViewById(R.id.radio_payment);
RadioGroup.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for (String paymentType: checkoutData.getPaymentTypes()) {
RadioButton radioButton = new RadioButton(getBaseContext());
radioButton.setText(paymentType);
paymentGroup.addView(radioButton, params);
}
如何按代码为第 2 组中的按钮归档相同的外观?
更新 1
我做了更多的测试。
我在以下配置中进行了测试。
- 模拟器 - Google Android 4.1.1:相同的行为
- 模拟器 - Google Android 2.3.4:行为相同,但所有 RadioButton 的图形都相同,但文本颜色仍然不同。我猜在这个版本的 Android 中,按钮只有一个图形。
- 设备 - Nexus One - Android Cyanogenmod 7 (Android 2.3.7):与使用 Android 2.3.4 的模拟器上的行为相同
当我通过在布局文件中添加一个按钮和两个以编程方式混合第二组时,结果仍然相同。第一个按钮(在布局中定义)看起来像预期的那样,其他两个按钮使用不同的按钮图形并具有不同的文本颜色。
【问题讨论】:
-
只是一个早期的想法。如何创建一个扩展 RadioButton 并在 XML 中设置
-
你在什么设备上运行代码。从模拟器运行它是否有同样的问题?什么 API?因为我的结果不一样。是同一个 ViewParent 中的 radiogroups。如果不是,viewparent 是否附加了特定的样式?
-
我目前正在使用带有 Android 4.1.1 的 Nexus S 进行开发。但我会在模拟器和其他设备上检查它,然后更新我的问题。
-
将@+id/radio_gender" 放在与@+id/radio_payment" 相同的ViewGroup 中,看看是否相同。如果是,那么 radio_gender 具有从父级附加的样式
-
两个 RadioGroup 具有相同的 ViewGroup 作为父级。
标签: android styles radio-button radio-group