簡體   English   中英

在Android中以編程方式添加到RadioGroup時,RadioButtons具有不同的樣式

[英]RadioButtons have a different style when added to a RadioGroup programmatically in Android

我正在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

我做了一些測試。

我已經在以下配置中進行了測試。

  • 模擬器 - 谷歌Android 4.1.1:相同的行為
  • 模擬器 - 谷歌Android 2.3.4:相同的行為,但所有RadioButtons的圖形是相同的,但文本顏色仍然不同。 我想在這個版本的Android中只有一個按鈕圖形。
  • 設備 - Nexus One - Android Cyanogenmod 7(Android 2.3.7):與使用Android 2.3.4的模擬器上的行為相同

當我通過在布局文件中添加一個按鈕和以編程方式添加兩個按鈕來混合第二組時,結果仍然相同。 第一個按鈕(在布局中定義)看起來像預期的,其他兩個按鈕使用不同的按鈕圖形並具有不同的文本顏色。

好的,我找到了解決問題的方法。

我使用了錯誤的上下文來創建RadioButton。

代替

RadioButton radioButton = new RadioButton(getBaseContext());

我必須使用

RadioButton radioButton = new RadioButton(getContext);

要么

RadioButton radioButton = new RadioButton(this); // this is the Activity

我不知道為什么我在這里使用了基本上下文,因為我之前從未使用它。 如果我沒記錯,那么Context對象可以包含有關Activity的布局樣式的信息。 我想當我使用基本上下文時,這些信息丟失了,因此單選按鈕的外觀不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM