Android - 以编程方式设置 TextView TextStyle?

发布于 2024-12-12 01:06:59 字数 352 浏览 0 评论 0原文

有没有办法以编程方式设置 TextViewtextStyle 属性?似乎没有 setTextStyle() 方法。

需要明确的是,我不是在谈论视图/小部件样式!我正在谈论以下内容:

<TextView
  android:id="@+id/my_text"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Hello World"
  android:textStyle="bold" />

Is there a way to set the textStyle attribute of a TextView programmatically? There doesn't appear to be a setTextStyle() method.

To be clear, I am not talking about View / Widget styles! I am talking about the following:

<TextView
  android:id="@+id/my_text"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Hello World"
  android:textStyle="bold" />

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

南街九尾狐 2024-12-19 01:06:59
textview.setTypeface(Typeface.DEFAULT_BOLD);

setTypeface 是属性textStyle。

正如 Shankar V 所补充的,要保留之前设置的字体属性,您可以使用:

textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
textview.setTypeface(Typeface.DEFAULT_BOLD);

setTypeface is the Attribute textStyle.

As Shankar V added, to preserve the previously set typeface attributes you can use:

textview.setTypeface(textview.getTypeface(), Typeface.BOLD);
我爱人 2024-12-19 01:06:59

假设您的values/styles.xml 上有一个名为RedHUGEText 的样式:

<style name="RedHUGEText" parent="@android:style/Widget.TextView">
    <item name="android:textSize">@dimen/text_size_huge</item>
    <item name="android:textColor">@color/red</item>
    <item name="android:textStyle">bold</item>
</style>

只需像往常一样在XMLlayout/your_layout.xml 文件中创建您的TextView,比方说:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" />

在您的Activity 的java 代码中执行以下操作

TextView textViewTitle = (TextView) findViewById(R.id.text_view_title);
textViewTitle.setTextAppearance(this, R.style.RedHUGEText);

:我!它应用了颜色、大小、重力等。我在 Android API 级别从 8 到 17 的手机和平板电脑上使用过它,没有任何问题。请注意,从 Android 23 开始,该方法已被弃用。上下文参数已被删除,因此最后一行需要是:

textViewTitle.setTextAppearance(R.style.RedHUGEText);

要支持所有 API 级别,请使用 androidX TextViewCompat

TextViewCompat.setTextAppearance(textViewTitle, R.style.RedHUGEText)

请记住...仅当样式为文本实际上取决于您的 Java 逻辑的条件,或者您正在使用代码“动态”构建 UI...如果不是,最好只是这样做:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" 
    style="@style/RedHUGEText" />

您始终可以按照自己的方式进行!

Let's say you have a style called RedHUGEText on your values/styles.xml:

<style name="RedHUGEText" parent="@android:style/Widget.TextView">
    <item name="android:textSize">@dimen/text_size_huge</item>
    <item name="android:textColor">@color/red</item>
    <item name="android:textStyle">bold</item>
</style>

Just create your TextView as usual in the XML layout/your_layout.xml file, let's say:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" />

And in the java code of your Activity you do this:

TextView textViewTitle = (TextView) findViewById(R.id.text_view_title);
textViewTitle.setTextAppearance(this, R.style.RedHUGEText);

It worked for me! And it applied color, size, gravity, etc. I've used it on handsets and tablets with Android API Levels from 8 to 17 with no problems. Note that as of Android 23, that method has been deprecated. The context argument has been dropped, so the last line would need to be:

textViewTitle.setTextAppearance(R.style.RedHUGEText);

To support all API levels use androidX TextViewCompat

TextViewCompat.setTextAppearance(textViewTitle, R.style.RedHUGEText)

Remember... this is useful only if the style of the text really depends on a condition on your Java logic or you are building the UI "on the fly" with code... if it doesn't, it is better to just do:

<TextView android:id="@+id/text_view_title" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content 
    android:text="FOO" 
    style="@style/RedHUGEText" />

You can always have it your way!

情栀口红 2024-12-19 01:06:59

搜索 setTextAppearancesetTextTypeface。 stackoverflow上有类似的问题: 如何在运行时更改 TextView 的样式< /a>

Search for setTextAppearance or also setTextTypeface. There is similar question on stackoverflow: How to change a TextView's style at runtime

策马西风 2024-12-19 01:06:59

实现此任务的方法有很多,如下:-

1.

String text_view_str = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!";
TextView tv = (TextView)findViewById(R.id.ur_text_view_id);
tv.setText(Html.fromHtml(text_view_str));

2.

tv.setTypeface(null, Typeface.BOLD);
tv.setTypeface(null, Typeface.ITALIC);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
tv.setTypeface(null, Typeface.NORMAL);

3.

SpannableString spannablecontent=new SpannableString(o.content.toString());
spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 
                         0,spannablecontent.length(), 0);
// set Text here
tt.setText(spannablecontent);

4.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>

 tv.setTextAppearance(getApplicationContext(), R.style.boldText);

或者如果你想通过xml

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"

So many way to achieve this task some are below:-

1.

String text_view_str = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!";
TextView tv = (TextView)findViewById(R.id.ur_text_view_id);
tv.setText(Html.fromHtml(text_view_str));

2.

tv.setTypeface(null, Typeface.BOLD);
tv.setTypeface(null, Typeface.ITALIC);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
tv.setTypeface(null, Typeface.NORMAL);

3.

SpannableString spannablecontent=new SpannableString(o.content.toString());
spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 
                         0,spannablecontent.length(), 0);
// set Text here
tt.setText(spannablecontent);

4.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>

 tv.setTextAppearance(getApplicationContext(), R.style.boldText);

or if u want through xml

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"
淡淡の花香 2024-12-19 01:06:59

Kotlin 版本

要保留当前字体以及文本样式:

textView.apply {
    setTypeface(typeface, Typeface.NORMAL)
    // or
    setTypeface(typeface, Typeface.BOLD)
    // or
    setTypeface(typeface, Typeface.ITALIC)
    // or
    setTypeface(typeface, Typeface.BOLD_ITALIC)
}

Kotlin Version

To retain current font in addition to text style:

textView.apply {
    setTypeface(typeface, Typeface.NORMAL)
    // or
    setTypeface(typeface, Typeface.BOLD)
    // or
    setTypeface(typeface, Typeface.ITALIC)
    // or
    setTypeface(typeface, Typeface.BOLD_ITALIC)
}
国粹 2024-12-19 01:06:59

这个问题在很多地方以多种不同的方式提出。我最初在这里回答了它,但我觉得它在这个线程中也相关(因为我最终 这里当我寻找答案时)。

这个问题没有单一的解决方案,但这对我的用例有用。问题是,“View(context, attrs, defStyle)”构造函数并不引用实际的样式,它需要一个属性。因此,我们将:

  1. 定义一个属性
  2. 创建一个您想要使用的样式
  3. 在我们的主题上应用该属性的样式
  4. 使用该属性创建视图的新实例

在“res/values/attrs.xml”中,定义一个新属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="customTextViewStyle" format="reference"/>
    ...
</resources>    

在 res/values/styles.xml' 中,我将创建要在自定义 TextView 上使用的样式

<style name="CustomTextView">
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:paddingLeft">14dp</item>
</style>

在 'res/values/themes.xml' 或 'res/values/styles.xml' 中,修改主题您的申请/活动以及添加以下样式:

<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <item name="@attr/customTextViewStyle">@style/CustomTextView</item>
    </style>
    ... 
</resources>

最后,在您的自定义 TextView 中,您现在可以使用带有该属性的构造函数,它将接收您的样式

public class CustomTextView extends TextView {

    public CustomTextView(Context context) {
       super(context, null, R.attr.customTextView);
    }
}

值得注意的是,我在不同的变体和不同的地方重复使用了 customTextView,但这绝不是必需的视图的名称与样式或属性或任何内容相匹配。此外,此技术应该适用于任何自定义视图,而不仅仅是 TextView。

This question is asked in a lot of places in a lot of different ways. I originally answered it here but I feel it's relevant in this thread as well (since i ended up here when I was searching for an answer).

There is no one line solution to this problem, but this worked for my use case. The problem is, the 'View(context, attrs, defStyle)' constructor does not refer to an actual style, it wants an attribute. So, we will:

  1. Define an attribute
  2. Create a style that you want to use
  3. Apply a style for that attribute on our theme
  4. Create new instances of our view with that attribute

In 'res/values/attrs.xml', define a new attribute:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="customTextViewStyle" format="reference"/>
    ...
</resources>    

In res/values/styles.xml' I'm going to create the style I want to use on my custom TextView

<style name="CustomTextView">
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:paddingLeft">14dp</item>
</style>

In 'res/values/themes.xml' or 'res/values/styles.xml', modify the theme for your application / activity and add the following style:

<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <item name="@attr/customTextViewStyle">@style/CustomTextView</item>
    </style>
    ... 
</resources>

Finally, in your custom TextView, you can now use the constructor with the attribute and it will receive your style

public class CustomTextView extends TextView {

    public CustomTextView(Context context) {
       super(context, null, R.attr.customTextView);
    }
}

It's worth noting that I repeatedly used customTextView in different variants and different places, but it is in no way required that the name of the view match the style or the attribute or anything. Also, this technique should work with any custom view, not just TextViews.

江心雾 2024-12-19 01:06:59

由于 setTextAppearance(resId) 仅适用于 API 23 及以上版本,因此请使用:

TextViewCompat.setTextAppearance(textViewGoesHere, resId)

该方法内部实现如下:

public static void setTextAppearance(@NonNull TextView textView, @StyleRes int resId) {
    if (Build.VERSION.SDK_INT >= 23) {
        textView.setTextAppearance(resId);
    } else {
        textView.setTextAppearance(textView.getContext(), resId);
    }
}

Since setTextAppearance(resId) is only available for API 23 and above, use:

TextViewCompat.setTextAppearance(textViewGoesHere, resId)

This method is internally implemented as follows:

public static void setTextAppearance(@NonNull TextView textView, @StyleRes int resId) {
    if (Build.VERSION.SDK_INT >= 23) {
        textView.setTextAppearance(resId);
    } else {
        textView.setTextAppearance(textView.getContext(), resId);
    }
}
千鲤 2024-12-19 01:06:59

这对我有用

textview.setTypeface(textview.getTypeface(), Typeface.BOLD);

textview.setTypeface(Typeface.DEFAULT_BOLD);

This worked for me

textview.setTypeface(textview.getTypeface(), Typeface.BOLD);

or

textview.setTypeface(Typeface.DEFAULT_BOLD);
夜灵血窟げ 2024-12-19 01:06:59

我用两种简单的方法解决了这个问题。

按照说明进行操作。

我现有的样式声明:

<style name="SearchInfoText">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textSize">24sp</item>
    <item name="android:textColor">@color/Church_Grey</item>
    <item name="android:shadowColor">@color/Shadow_Church</item>
    <item name="android:shadowRadius">3</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
</style>

我的 Android Java 代码:

    TextView locationName = new TextView(getSupportActivity());
    locationName.setId(IdGenerator.generateViewId());
    locationName.setText(location.getName());
    locationName.setLayoutParams(super.centerHorizontal());
    locationName.setTextSize(24f);
    locationName.setPadding(0, 0, 0, 15);
    locationName.setTextColor(getResources().getColor(R.color.Church_Grey));
    locationName.setShadowLayer(3, 1, 1,  getResources().getColor(R.color.Shadow_Church));

问候。

I´ve resolved it with two simple methods.

Follow the explanation.

My existing style declaration:

<style name="SearchInfoText">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textSize">24sp</item>
    <item name="android:textColor">@color/Church_Grey</item>
    <item name="android:shadowColor">@color/Shadow_Church</item>
    <item name="android:shadowRadius">3</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
</style>

My Android Java code:

    TextView locationName = new TextView(getSupportActivity());
    locationName.setId(IdGenerator.generateViewId());
    locationName.setText(location.getName());
    locationName.setLayoutParams(super.centerHorizontal());
    locationName.setTextSize(24f);
    locationName.setPadding(0, 0, 0, 15);
    locationName.setTextColor(getResources().getColor(R.color.Church_Grey));
    locationName.setShadowLayer(3, 1, 1,  getResources().getColor(R.color.Shadow_Church));

Regards.

凤舞天涯 2024-12-19 01:06:59

你可以试试这个

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                textView.setTextAppearance(R.style.Lato_Bold);
            } else {
                textView.setTextAppearance(getActivity(), R.style.Lato_Bold);
            }

You may try this one

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                textView.setTextAppearance(R.style.Lato_Bold);
            } else {
                textView.setTextAppearance(getActivity(), R.style.Lato_Bold);
            }
丢了幸福的猪 2024-12-19 01:06:59

用于更改样式而不更改字体的 Kotlin 扩展函数:

fun TextView.setTextStyle(style: Int) {
    typeface = when (style) {
        Typeface.NORMAL,
        Typeface.BOLD,
        Typeface.ITALIC,
        Typeface.BOLD_ITALIC -> Typeface.create(typeface, style)

        else -> throw IllegalArgumentException("Invalid text style. Use NORMAL, BOLD, ITALIC, or BOLD_ITALIC")
    }
}

用法:

textView.setTextStyle(Typeface.BOLD_ITALIC)

Kotlin extension function for changing style without changing typeface:

fun TextView.setTextStyle(style: Int) {
    typeface = when (style) {
        Typeface.NORMAL,
        Typeface.BOLD,
        Typeface.ITALIC,
        Typeface.BOLD_ITALIC -> Typeface.create(typeface, style)

        else -> throw IllegalArgumentException("Invalid text style. Use NORMAL, BOLD, ITALIC, or BOLD_ITALIC")
    }
}

Usage:

textView.setTextStyle(Typeface.BOLD_ITALIC)
愁杀 2024-12-19 01:06:59

正如此处所述,此功能目前不支持。

As mentioned here, this feature is not currently supported.

迎风吟唱 2024-12-19 01:06:59

这对我有用

msg.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
OR
TextView.setTypeface(msg.getTypeface(),Typeface.NORMAL);

而不是关闭

TextView.setTypeface(Typeface.DEFAULT_BOLD);

This Works For Me

msg.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
OR
TextView.setTypeface(msg.getTypeface(),Typeface.NORMAL);

Instead Off

TextView.setTypeface(Typeface.DEFAULT_BOLD);
病毒体 2024-12-19 01:06:59

使用数据绑定和 Kotlin

@BindingAdapter("textViewStyle")
fun TextView.bindTextViewStyle(styleResourceId: Int) {
    TextViewCompat.setTextAppearance(this, styleResourceId)
}

XML

 <TextView
   android:layout_width="wrap_content"
   android:text="test text"
   bind:textViewStyle="@{styleResId}" />

Using data binding and Kotlin

@BindingAdapter("textViewStyle")
fun TextView.bindTextViewStyle(styleResourceId: Int) {
    TextViewCompat.setTextAppearance(this, styleResourceId)
}

XML

 <TextView
   android:layout_width="wrap_content"
   android:text="test text"
   bind:textViewStyle="@{styleResId}" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文