设置以编程方式添加的视图的样式 [英] Setting styles of programmatically added Views

查看:68
本文介绍了设置以编程方式添加的视图的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我以编程方式将输入元素(例如radioButtons,复选框等)添加到Layout中. 问题是,当您通过xml添加单选按钮时,这些元素的样式不是您将获得的默认样式. (它看起来真的是白色的,在白色应用程序背景下几乎是透明的.有点像是透明的) 另外,我要添加的EditText元素具有相同的样式,如果您在其中键入内容,则文本太大,并且文本行会有点重叠. 因此,我想这全都归结为这些元素的默认样式,就像它们通过xml定义时一样.

In my code, I add input elements like radioButtons, checkboxes etc to my Layout programmatically. The problem is, that the style of those elements is not the default style that you would get, when you would add let's say a radioButton via xml. (It looks really white and almost see-through on a white application background. A bit like it is transparent) Also, the EditText elements I'm adding have the same style and if you type something in them, the text is too big and overlaps the text line a bit. So I guess it all comes down to somehow giving those elements their default style, like they look when defined via 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(棒棒糖)

My target API lvl is 21 (Lollipop)

推荐答案

您可以传递在styles.xml内部定义的样式作为View构造函数的参数.因此,考虑您的示例,您必须致电:

You can pass a style defined inside styles.xml as an argument of a View constructor. So considering your example, you would have to call:

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

然后在attrs.xml

<attr name="radioButtonStyle" format="reference" />

,然后在您的应用程序主题内的styles.xml添加

and inside your application theme in styles.xml add

<item name="radioButtonStyle">@style/YourRadioButtonStyle</item>

YourRadioButtonStyle是在styles.xml

这篇关于设置以编程方式添加的视图的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆