Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have multiple styles inside a TextView?

Is it possible to set multiple styles for different pieces of text inside a TextView?

For instance, I am setting the text as follows:

tv.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3); 

Is it possible to have a different style for each text element? E.g., line1 bold, word1 italic, etc.

The developer guide's Common Tasks and How to Do Them in Android includes Selecting, Highlighting, or Styling Portions of Text:

// Get our EditText object. EditText vw = (EditText)findViewById(R.id.text);  // Set the EditText's text. vw.setText("Italic, highlighted, bold.");  // If this were just a TextView, we could do: // vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE); // to force it to use Spannable storage so styles can be attached. // Or we could specify that in the XML.  // Get the EditText's internal text storage Spannable str = vw.getText();  // Create our span sections, and assign a format to each. str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

But that uses explicit position numbers inside the text. Is there a cleaner way to do this?

like image 319
Legend Avatar asked Oct 07 '09 01:10

Legend


People also ask

Can we Nest TextView inside TextView?

In Android all layout can be nested one another.

How do you add multiple lines in TextView?

When you have a text that's longer than one line, then the TextView will automatically put the text in multiple lines. When you set the layout_width and layout_height as wrap_content or match_parent , then the TextView widget will use all the available space to display the text you specified as its content.

What is the difference between an EditText and a TextView?

EditText is used for user input. TextView is used to display text and is not editable by the user. TextView can be updated programatically at any time.


1 Answers

In case, anyone is wondering how to do this, here's one way: (Thanks to Mark again!)

mBox = new TextView(context); mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" +              "<small>" + description + "</small>" + "<br />" +              "<small>" + DateAdded + "</small>")); 

For an unofficial list of tags supported by this method, refer to this link or this question: Which HTML tags are supported by Android TextView?

like image 54
Legend Avatar answered Sep 27 '22 22:09

Legend