设置以编程方式添加的视图的样式

Setting styles of programmatically added Views

在我的代码中,我以编程方式将单选按钮、复选框等输入元素添加到布局中。 问题是,当您通过 xml 添加一个 radioButton 时,这些元素的样式不是您将获得的默认样式。 (在白色的应用背景下看起来真的很白,几乎是透明的,有点像透明) 此外,我添加的 EditText 元素具有相同的样式,如果您在其中键入内容,文本会太大并与文本行重叠一点。 所以我想这一切都归结为以某种方式为这些元素提供了默认样式,就像它们通过 xml.

定义时的外观一样

我的代码示例如下所示:

RadioGroup radioGroup = new RadioGroup(mContext);
    radioGroup.setLayoutParams(fullWidthWrapHeight);

    for (int i = 0; i < arg0.getOptions().size(); i++){
        RadioButton radioButton = new RadioButton(mContext, null);
        radioButton.setPadding(padding16dp , padding8dp, padding16dp, padding8dp);
        radioButton.setText(arg0.getOptions().get(i).getText());
        radioButton.setLayoutParams(wrapBoth);
        radioButton.setGravity(Gravity.CENTER_HORIZONTAL);

        radioButton.setTextAppearance(mContext, R.style.Default_Text);
        radioGroup.addView(radioButton);
    }

我的目标 API 等级是 21(棒棒糖)

您可以将 styles.xml 中定义的样式作为 View 构造函数的参数传递。因此,考虑到您的示例,您必须调用:

RadioButton radioButton = new RadioButton(mContext, null, R.attr.radioButtonStyle);

然后在 attrs.xml

中添加自定义属性
<attr name="radioButtonStyle" format="reference" />

并在 styles.xml 中添加

中的应用程序主题
<item name="radioButtonStyle">@style/YourRadioButtonStyle</item>

YourRadioButtonStyle 是在 styles.xml

中定义的自定义单选按钮样式

我的就这样成功解决了:

Activity.java

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

...

    { 
        RadioButton rb = (RadioButton) inflater.inflate(R.layout.radio_butt, null);
        rb.setText(this_currency_option);
        rb.setTextColor(context.getResources().getColor(R.color.colorWhite));
        rb.setId(100 + i);
        radioGroup.addView(rb);
    }

radio_butt.xml

<?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:textSize="14sp"
    android:textColor="@color/colorWhite"
    android:theme="@style/MyRadioButtonStyle"/>

slyles.xml

<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="colorControlNormal">@color/colorAlfaWhite</item>
    <item name="colorControlActivated">@color/colorWhite</item>
</style>