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

时间:2015-01-20 13:45:35

标签: android android-styles programmatically-created

在我的代码中,我以编程方式向我的Layout添加了radioButtons,checkboxes等输入元素。 问题是,这些元素的样式不是你会得到的默认样式,当你添加时,让我们通过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 lvl是21(Lollipop)

2 个答案:

答案 0 :(得分:12)

您可以将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>

YourRadioButtonStylestyles.xml

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

答案 1 :(得分:0)

至于我,它已经成功解决了这个问题:

<强> 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>
相关问题