Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 420
Cris Avatar asked Jan 07 '11 21:01

Cris


People also ask

How change TextView text from another activity?

You have to use Intent to make action in another activity. textView. setText(btn_text);

How do I change my style on android?

Changing the style after creating the view is not supported .. so what you can do is: create a new android xml file of type values. add new theme. add your elements to that theme and their values and save the file.


2 Answers

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. 
like image 41
DKDiveDude Avatar answered Oct 02 '22 12:10

DKDiveDude


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 image 84
Glenn Avatar answered Oct 02 '22 10:10

Glenn