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

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


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


textview.setTextAppearance();

但它不起作用。


慕尼黑8549860
浏览 298回答 3
3回答

慕沐林林

我通过创建一个新的XML文件res/values/style.xml来做到这一点,如下所示:<?xml version="1.0" encoding="utf-8"?><resources>&nbsp; &nbsp; <style name="boldText">&nbsp; &nbsp; &nbsp; &nbsp; <item name="android:textStyle">bold|italic</item>&nbsp; &nbsp; &nbsp; &nbsp; <item name="android:textColor">#FFFFFF</item>&nbsp; &nbsp; </style>&nbsp; &nbsp; <style name="normalText">&nbsp; &nbsp; &nbsp; &nbsp; <item name="android:textStyle">normal</item>&nbsp; &nbsp; &nbsp; &nbsp; <item name="android:textColor">#C0C0C0</item>&nbsp; &nbsp; </style></resources>我的“ strings.xml”文件中也有一个条目,如下所示:<color name="highlightedTextViewColor">#000088</color><color name="normalTextViewColor">#000044</color>然后,在我的代码中,我创建了一个ClickListener来捕获该TextView上的tap事件: 编辑: 自API 23起,不建议使用setTextAppearance&nbsp; &nbsp; myTextView.setOnClickListener(new View.OnClickListener() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void onClick(View view){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //highlight the TextView&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);&nbsp; &nbsp; if (Build.VERSION.SDK_INT < 23) {&nbsp; &nbsp; &nbsp; &nbsp;myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp;myTextView.setTextAppearance(R.style.boldText);&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;myTextView.setBackgroundResource(R.color.highlightedTextViewColor);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });要将其改回,可以使用以下方法:if (Build.VERSION.SDK_INT < 23) {&nbsp; &nbsp; myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);} else{&nbsp; &nbsp;myTextView.setTextAppearance(R.style.normalText);}myTextView.setBackgroundResource(R.color.normalTextViewColor);

烙印99

就像乔纳森(Jonathan)建议的那样,在使用textView.setTextTypeface作品的同时,我只是在几秒钟前在一个应用程序中使用过它。textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.

收到一只叮咚

以编程方式:运行时您可以使用setTypeface()以编程方式进行操作:textView.setTypeface(null, Typeface.NORMAL);&nbsp; &nbsp; &nbsp; // for Normal TexttextView.setTypeface(null, Typeface.BOLD);&nbsp; &nbsp; &nbsp; &nbsp; // for Bold onlytextView.setTypeface(null, Typeface.ITALIC);&nbsp; &nbsp; &nbsp; // for ItalictextView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and ItalicXML:设计时间您还可以设置XML:android:textStyle="normal"android:textStyle="normal|bold"android:textStyle="normal|italic"android:textStyle="bold"android:textStyle="bold|italic"希望这会有所帮助总结
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java