我试图使用TextView构造函数的风格像这样:

TextView myText = new TextView(MyActivity.this, null, R.style.my_style);

但是,当我这样做时,文本视图似乎没有采用该样式(我通过在静态对象上设置该样式来验证该样式)。

我还尝试使用myText.setTextAppearance(MyActivity. settextappearance)。this, R.style.my_style),但它也不能工作。


当前回答

我也遇到过这个问题,我找到了以编程方式设置样式的方法。也许你们都需要,所以我在这里更新。

视图构造函数的第三个参数接受主题中的attr类型,如下所示:

public TextView(Context context, AttributeSet attrs) {
    this(context, attrs, com.android.internal.R.attr.textViewStyle);
}

所以你必须传递一个类型的r。attr。**而不是R.style.**

在我的代码中,我做了以下步骤:

首先,自定义一个自定义attr,供attr.xml中的主题使用。

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

其次,在style.xml中指定您使用的主题的样式。

 <style name="AppTheme" parent="android:Theme.Translucent">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="radio_button_style">@style/radioButtonStyle</item>
</style>
<style name="radioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">64dp</item>
    <item name="android:background">#000</item>
    <item name="android:button">@null</item>
    <item name="android:gravity">center</item>
    <item name="android:saveEnabled">false</item>
    <item name="android:textColor">@drawable/option_text_color</item>
    <item name="android:textSize">9sp</item>
</style>

最后,使用它!

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

以编程方式创建的视图将在主题中使用指定的样式。

你可以试一试,希望它能完美地为你工作。

其他回答

我只使用EditText进行了测试,但您可以使用该方法

setBackgroundResource (int residual)

来应用XML文件中定义的样式。

因为这个方法属于视图,我相信它将适用于任何UI元素。

的问候。

你可以像这样将ContextThemeWrapper传递给构造函数:

TextView myText = new TextView(new ContextThemeWrapper(MyActivity.this, R.style.my_style));

我们可以使用TextViewCompact。setTextAppearance (textView R.style.xyz)。

Android文档供参考。

这个公认的答案对我来说是一个很好的解决方案。唯一要添加的是关于inflation()方法。

在接受的答案中,所有android:layout_*参数将不会被应用。

原因是没有办法调整它,因为null是作为ViewGroup父项传递的。

你可以这样使用它:

视图视图= inflater. inflation (r.p ayler .layout。View, parent, false);

父类是ViewGroup,从这里你可以调整android:layout_*。

在这种情况下,将设置所有相关属性。

希望对别人有用。

当使用可能使用样式继承(或事件可样式属性)的自定义视图时,您必须修改第二个构造函数,以免丢失样式。这对我来说很有效,不需要使用settextappearance ():

public CustomView(Context context, AttributeSet attrs) {
    this(context, attrs, attrs.getStyleAttribute());
}