0

Looking to style (bold, italic etc.) "quote" and "name", but have tried several potential solutions with no luck:

       private void settextView(String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);
        String[] tasks = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            tasks[i] = obj.getString("quote") + "\n\n" + obj.getString("name");

            textView.setText(tasks[0]);
            setBtnCopyOnClick(tasks[0]); //Here

            String a = "quote";

            SpannableString spanned = new SpannableString(a);
            spanned.setSpan(new UnderlineSpan(), 1, a.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        }
    }

They both generate in the same textView, so unfortunately I can only style all, or not at all.

1 Answers1

1

If you are looking to style only specific parts of text you should be using spans. The Android Developers site has good documentation on this which you can read here.

For your particular use case pay most attention to the StyleSpan which allows you to set Typeface flags.

For example:

String a = "underlined text";
String b = " normal text";

SpannableString spanned = new SpannableString(a + b);
spanned.setSpan(new UnderlineSpan(), 0, a.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
Henry Twist
  • 5,666
  • 3
  • 19
  • 44
  • Hmm, looks like an interesting method however each time the above code is ran, the amount of characters change - therefore specifying style for number of characters would be challenging, unless I've read something wrong? It'd be great to understand if i can just get "+ obj.getString("name");" in bold. – sgccommander Mar 03 '21 at 08:52
  • Sorry I'm not sure what you mean by it being challenging? Surely you can just set the span to be the length of the string itself? – Henry Twist Mar 03 '21 at 10:13
  • Do you mean setting a span for the length of the result, or the title (i.e. "name"). As mentioned, each time the above code is ran, the length of characters change. Sorry if I have misinterpreted what you've suggested! – sgccommander Mar 03 '21 at 10:23
  • Let me include an example in my answer – Henry Twist Mar 03 '21 at 10:24
  • Unfortunately this did not work, i have updated my original question with updated code as per your instruction. – sgccommander Mar 03 '21 at 15:13
  • I presume you are setting the text to the new spanned string, `textView.setText(spanned);`? – Henry Twist Mar 03 '21 at 15:19
  • Yes, however "spanned" comes up in red (thinking face) – sgccommander Mar 03 '21 at 21:17