How to change a TextView's style at runtime
I have an android app on which, when the user taps a TextView
, I would like to apply a defined style.
I thought to find a textview.setStyle()
but it doesn't exists. I tried
textview.setTextAppearance();
but it does not work.
Solution 1:
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);
Solution 2:
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.