Search code examples
javaandroidstringtextview

set some text of a string at the center of a TextView


I want to fix some text of string in the center. How can I do that? For example, take a look on this photo

Heading at the center

I have a string like that. Now I want some words (Heading) of my string to be shown in a TextView at the center horizontally but others word will remain as usual. How can I do that?

I have tried the following code but it doesn't work for various dimension's devices.

          String string= "                 SYRIA
\n\nSyria oh Syria why do you bleed?
        \nBrother fights brother without thought or need
    \nRuled by a tyrant for so many years
    \nAnd now the split blood is washed away by tears\n"

Solution

  • You can wither use 2 different Textviews or If there is single textview, you can use HTML or Spannable String for that. Spannable can be used as follows:

    TextView resultView = new TextView(this);
    final String SyriaText = "Syria";
    final String OtherText = "Other Text";
    final String result = SyriaText + "  " + OtherText;
    final SpannableString finalResult = new SpannableString(result);
    finalResult.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_CENTER), 0, SyriaText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    resultView.setText(finalResult);
    

    Also you can style it with Spannable. You can learn more from : https://developer.android.com/reference/android/text/Spannable.html