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

Cri*_*ris 97 java android textview

我有一个Android应用程序,当用户点击一个TextView,我想应用一个定义的样式.

我想找到一个,textview.setStyle()但它不存在.我试过了

textview.setTextAppearance();
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

Gle*_*enn 142

我这样做是通过创建一个新的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>
Run Code Online (Sandbox Code Playgroud)

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

<color name="highlightedTextViewColor">#000088</color>
<color name="normalTextViewColor">#000044</color>
Run Code Online (Sandbox Code Playgroud)

然后,在我的代码中,我创建了一个ClickListener来捕获该TextView上的tap事件: 编辑: 从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);
                }
            });
Run Code Online (Sandbox Code Playgroud)

要将其更改回来,您可以使用:

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

  • 要避免SDK检查,可以使用TextViewCompat.setTextAppearance(myTextView,R.style.myStyle); (3认同)
  • 实际上这不适用于阴影样式.如果你想改变阴影,你必须这样做:lockText.setShadowLayer(20,4,4,0xFFFF0000); (2认同)

DKD*_*ude 90

就像Jonathan建议的那样,使用textView.setTextTypeface作品,我几秒钟之前就在应用程序中使用过它.

textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用textView.setTypeface(null,Typeface.BOLD); textView..setTypeface(null,Typeface.ITALIC); textView.setTypeface(null,Typeface.BOLD_ITALIC); (9认同)
  • 不要鼓励人们使用int而不是常量 (4认同)
  • textView.setTypeface(null,Typeface.BOLD)对我有用.当然,您可以使用1代替,但我想手动输入常量并不是一个好习惯.更好地使用库中的预定义变量. (2认同)
  • 好的!我的错误是我在第一个参数中发送了我的旧字体.因此,当我改变NORMAL - > BOLD但不是BOLD - > NORMAL时,它确实有用.我不知道第一个参数可能为null!现在它对我来说很好! (2认同)

Azh*_*har 12

TextView tvCompany = (TextView)findViewById(R.layout.tvCompany);
tvCompany.setTypeface(null,Typeface.BOLD);
Run Code Online (Sandbox Code Playgroud)

你可以从代码中设置它.字体