Formatting text as a string

I have this line:

    String[] text = {"Address 1: Street nr.45 ",
         "Address 2: Street nr.67",
         "Address 3: Street nr. 56 \n Phone number: 000000000"};

      

which will be used later:

        ((TextView)findViewById(R.id.adresa)).setText(text[newSelectedAddress]);

      

when selecting an item from the counter.

How do I add formatting to text within a string? I want the address to be bold, street no. with italics

+3


source to share


3 answers


You must use Spannable

s. While their creation is a bit verbose and seems complicated, this is not rocket science. Example:

String source = "This is example text";
SpannedString out = new SpannedString(source);
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
StyleSpan boldSpan2 = new StyleSpan(Typeface.BOLD);
out.setSpan(boldSpan, 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
out.setSpan(boldSpan2, 9, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

      



Result: T hi s is e xam text

Then setText

this Spannable instead of the usual string.

+3


source


Do this, my dear friend:

String[] text = {"Address 1: Street nr.45 ",
             "Address 2: Street nr.67",
             "Address 3: Street nr. 56 \n Phone number: 000000000"};
    String tempString = text[newSelectedAddress];
    CharSequence charSeq= new SpannedString(tempString);
    Spannable spannable = (Spannable) charSeq;
    StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
    StyleSpan boldSpan2 = new StyleSpan(Typeface.ITALIC);
    spannable.setSpan(boldSpan, 0, "Address".length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(boldSpan2, tempString.indexOf("Street"), tempString.indexOf("Street")-1 +"Street".length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    ((TextView)findViewById(R.id.adresa)).setText(spannable);

      



thank

+1


source


There's a bit of a hack there so that strings can recognize html for bold and italic formatting. Add something like this to your .xml lines:

<string name="address"><![CDATA[<b>Address %1$s</b>: <i>Street nr. %2$s </i>]]></string>

      

Then:

Resources res = getResources();
formattedString = res.getString(R.string.address, "1", "45");
// equivalent to String.format(res.getString(R.string.address), "1", "45")
Spannable s = Html.from Html(formattedString);
textView.setText(s);

      

0


source







All Articles