Issue
I've been struggling with the idea of adding different (font sizes, and alignments) for different parts of a String in the same TextView.
What I want exactly could be shown in the picture below where I want the first line in the TextView to be centered and with a size that could be set programmatically.
Also, from the second line, I want the text to be left-aligned and set to a limit of 12 characters per line.
So, how to do this?
This is the XML code for the TextView and it is being added inside a LinearLayout tag :
<TextView
android:id="@+id/tray1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".70"
android:background="#B38888"
android:text="トレイ1"
android:textAlignment="viewStart"
android:textSize="20sp"
android:textStyle="bold" />
Solution
I was able to do that using the power of SpannableStringBuilder
SpannableStringBuilder str = new SpannableStringBuilder("PUT YOUR STRING HERE");
// set part of the str to bold
str.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), fromIndex, toIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// set part of the str to bigger size
str.setSpan(new RelativeSizeSpan(2f), fromIndex, toIndex, 0);
// set alignment of it to center
str.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), fromIndex, toIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
activeTray.setText(str);
NOTE: you need to specify the integers fromIndex & toIndex where they represent the indexes of the character inside the PUT YOUR STRING HERE
Answered By - Mohamad Ghaith Alzin
Answer Checked By - Pedro (JavaFixing Volunteer)