如何在运行时更改 TextView 的样式 [英] How to change a TextView's style at runtime
问题描述
我有一个 android 应用,当用户点击 TextView
时,我想应用一个定义的样式.
I have an android app on which, when the user taps a TextView
, I would like to apply a defined style.
我想找到一个 textview.setStyle()
但它不存在.我试过
I thought to find a textview.setStyle()
but it doesn't exists. I tried
textview.setTextAppearance();
但它不起作用.
推荐答案
我通过创建一个新的 XML 文件 res/values/style.xml
来做到这一点,如下所示:
I did this by creating a new XML file res/values/style.xml
as follows:
<?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"文件中也有这样的条目:
I also have an entries in my "strings.xml" file like this:
<color name="highlightedTextViewColor">#000088</color>
<color name="normalTextViewColor">#000044</color>
然后,在我的代码中,我创建了一个 ClickListener 来捕获该 TextView 上的点击事件:从 API 23 开始,不推荐使用setTextAppearance"
Then, in my code I created a ClickListener to trap the tap event on that TextView: As from API 23 'setTextAppearance' is deprecated
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);
}
});
要将其改回来,您可以使用:
To change it back, you would use this:
if (Build.VERSION.SDK_INT < 23) {
myTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
} else{
myTextView.setTextAppearance(R.style.normalText);
}
myTextView.setBackgroundResource(R.color.normalTextViewColor);
这篇关于如何在运行时更改 TextView 的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!