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

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

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

textview.setTextAppearance();

但是没有用。

106305 次浏览

See doco for setText() in TextView http://developer.android.com/reference/android/widget/TextView.html

To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.

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>

I also have an entries in my "strings.xml" file like this:

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

Then, in my code I created a ClickListener to trap the tap event on that TextView: EDIT: 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);

Like Jonathan suggested, using textView.setTextTypeface works, I just used it in an app a few seconds ago.

textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.
TextView tvCompany = (TextView)findViewById(R.layout.tvCompany);
tvCompany.setTypeface(null,Typeface.BOLD);

You an set it from code. Typeface

i found textView.setTypeface(Typeface.DEFAULT_BOLD); to be the simplest method.

Depending on which style you want to set, you have to use different methods. TextAppearance stuff has its own setter, TypeFace has its own setter, background has its own setter, etc.

try this line of code.

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

here , it will get current Typeface from this textview and replace it using new Typeface. New typeface here is DEFAULT_BOLD but you can apply many more.