如何在运行时更改 TextView 的样式

问题描述 投票:0回答:8

我有一个 Android 应用程序,当用户点击

TextView
时,我想应用定义的样式。

我想找到一个

textview.setStyle()
,但它不存在。我试过了

textview.setTextAppearance();

但是不起作用。

java android textview
8个回答
144
投票

我通过创建一个新的 XML 文件来完成此操作

res/values/style.xml
,如下所示:

<?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>

我的“strings.xml”文件中也有一个条目,如下所示:

<color name="highlightedTextViewColor">#000088</color>
<color name="normalTextViewColor">#000044</color>

然后,在我的代码中,我创建了一个 ClickListener 来捕获该 TextView 上的点击事件: 编辑: 从 API 23 开始,'setTextAppearance' 已被弃用

    myTextView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view){
                    //highlight the TextView
                    //myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    if (Build.VERSION.SDK_INT < 23) {
       myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
    } else {
       myTextView.setTextAppearance(R.style.boldText);
    }
     myTextView.setBackgroundResource(R.color.highlightedTextViewColor);
                }
            });

要将其改回来,您可以使用以下命令:

if (Build.VERSION.SDK_INT < 23) {
    myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
} else{
   myTextView.setTextAppearance(R.style.normalText);
}
myTextView.setBackgroundResource(R.color.normalTextViewColor);

91
投票

就像乔纳森建议的那样,使用

textView.setTextTypeface
有效,我几秒钟前刚刚在应用程序中使用了它。

textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.

12
投票
TextView tvCompany = (TextView)findViewById(R.layout.tvCompany);
tvCompany.setTypeface(null,Typeface.BOLD);

您可以通过代码进行设置。 字体


2
投票

我发现

textView.setTypeface(Typeface.DEFAULT_BOLD);
是最简单的方法。


1
投票

尝试这行代码。

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

在这里,它将从此文本视图获取当前的字体,并使用新的字体替换它。这里的新字体是

DEFAULT_BOLD
,但您可以应用更多。


0
投票

参见 TextView 中 setText() 的 doco http://developer.android.com/reference/android/widget/TextView.html

要设置字符串样式,请将 android.text.style.* 对象附加到 SpannableString,或参阅可用资源类型文档以获取在 XML 资源文件中设置格式化文本的示例。


0
投票

根据你想要设置哪种风格,你必须使用不同的方法。 TextAppearance 东西有自己的 setter,TypeFace 有自己的 setter,background 有自己的 setter,等等


0
投票

我曾经得到过在 Android 中将单词加粗的最简单方法。我记得它说突出显示该单词,在其上点击两次,然后点击格式,然后点击“B”或“b”。问题是我不太记得如何再次执行此操作并希望这里有人可能知道这个公式?先感谢您。 :) 阿德拉

© www.soinside.com 2019 - 2024. All rights reserved.