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

Cud*_*l3s 6 android android-styles programmatically-created

在我的代码中,我以编程方式向我的Layout添加了radioButtons,checkboxes等输入元素.问题是,这些元素的样式不是你可以获得的默认样式,当你通过xml添加let说一个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);
    }
Run Code Online (Sandbox Code Playgroud)

我的目标API lvl是21(Lollipop)

Bar*_*ski 13

您可以将内部定义的样式styles.xml作为View构造函数的参数传递.所以考虑你的例子,你必须打电话:

RadioButton radioButton = new RadioButton(mContext, null, R.attr.radioButtonStyle);
Run Code Online (Sandbox Code Playgroud)

然后在里面添加自定义属性 attrs.xml

<attr name="radioButtonStyle" format="reference" />
Run Code Online (Sandbox Code Playgroud)

并在你的应用程序主题中styles.xml添加

<item name="radioButtonStyle">@style/YourRadioButtonStyle</item>
Run Code Online (Sandbox Code Playgroud)

YourRadioButtonStyle 是定义的自定义单选按钮样式 styles.xml