Set text of different styles in the same TextView of Android
Requirement Analysis:
Most of the time, we need to display text of different styles in the view, but in order to reduce the viewgroup level, we do not want to add many TextView controls to implement text of different styles.
Is there a way to implement multiple custom style texts in the same TextView control?
The answer is yes. Let's do a practical experiment on this issue.
Practice process:
First, we define three TextView controls in the layout xml file. Their definitions are as follows:
Next, we use a key class such as SpannableString in java code to implement our requirements:
String rateContent = t. getAnnualizedRateOfReturn () + %; int lenRate = rateContent. length (); SpannableString rate = new SpannableString (rateContent); rate. setSpan (new TextAppearanceSpan (getActivity (), R. style. item_rate_text_style1), 0, lenRate-1, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE); rate. setSpan (new TextAppearanceSpan (getActivity (), R. style. item_rate_text_style2), lenRate-1, lenRate, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE); String monthsContent = String. valueOf (t. getMonths () + months; int lenMonths = monthsContent. length (); SpannableString months = new SpannableString (monthsContent); months. setSpan (new TextAppearanceSpan (getActivity (), R. style. item_month_sum_text_style1), 0, lenMonths-2, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE); months. setSpan (new TextAppearanceSpan (getActivity (), R. style. item_month_sum_text_style2), lenMonths-2, lenMonths, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE); String sumContent = String. valueOf (t. getSum () + 10 million RMB; int lenSum = sumContent. length (); SpannableString sum = new SpannableString (sumContent); sum. setSpan (new TextAppearanceSpan (getActivity (), R. style. item_month_sum_text_style1), 0, lenSum-1, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE); sum. setSpan (new TextAppearanceSpan (getActivity (), R. style. item_month_sum_text_style2), lenSum-1, lenSum, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE); Vl. setText (R. id. name_text, t. getName () + (+ t. getDate () + )). setStyledText (R. id. annualized_Rate_text, rate ). setStyledText (R. id. due_time_text, months ). setStyledText (R. id. total_sum_text, sum );
The setStyledText method is actually encapsulated. The setText method of the TextView control. String on the Span side is a subclass of the entire CharSequence class, so it can be used as a parameter of the setText method.
Here we use four styles, which are defined in the styles. xml file as follows:
Final effect, such:
We can see that there are two different styles in the same TextView.
Finally, I hope this article will help readers.