我有一个Android应用程序,在用户点击 TextView
时,我想应用一个定义好的样式。
我尝试过寻找 textview.setStyle()
,但它并不存在。我尝试了...
textview.setTextAppearance();
但是它不起作用。
我有一个Android应用程序,在用户点击 TextView
时,我想应用一个定义好的样式。
我尝试过寻找 textview.setStyle()
,但它并不存在。我尝试了...
textview.setTextAppearance();
但是它不起作用。
我通过创建一个新的 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);
像Jonathan建议的那样,使用textView.setTextTypeface
可以解决问题。我只是在几秒钟之前在一个应用程序中使用了它。
textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.
TextView tvCompany = (TextView)findViewById(R.layout.tvCompany);
tvCompany.setTypeface(null,Typeface.BOLD);
您可以通过代码设置它。 Typeface
textView.setTypeface(Typeface.DEFAULT_BOLD);
是最简单的方法。尝试这行代码。
textview.setTypeface(textview.getTypeface(), Typeface.DEFAULT_BOLD);
DEFAULT_BOLD
,但您可以应用更多。根据您想要设置的样式,您必须使用不同的方法。TextAppearance有自己的setter,TypeFace有自己的setter,背景有自己的setter等。
查看TextView中setText()的文档 http://developer.android.com/reference/android/widget/TextView.html
要为字符串设置样式,请将android.text.style.*对象附加到SpannableString上,或者参见“可用资源类型”文档以了解在XML资源文件中设置格式化文本的示例。