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

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

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

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


当前回答

不支持动态更改样式。您必须在创建视图之前通过XML设置样式。

其他回答

您可以在构造函数中设置样式(但样式不能动态更改/设置)。

视图(Context, AttributeSet, int) (int是当前主题中的属性,包含对样式的引用)

罗曼·盖伊的回答

参考

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
    textView.setTextAppearance(R.style.yourStyle)

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

视图构造函数的第三个参数接受主题中的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);

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

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

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

Android文档供参考。

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

setBackgroundResource (int residual)

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

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

的问候。