I have this TextView
. Some parts of it is supposed to be aligned to the left and some parts to the right. How would I do this in Java?
Basicly I want the first line to align to the left, and the next line to the right and so on.
Anyone got a clue?
EDIT
I have tried to use HTML and then when that did not work I tried spans.
html attempt
textView.setText(Html.fromHtml("<p align=\"right\">THIS IS TO THE RIGHT</p>"));
And heres the span attempt
String LeftText = "LEFT";
String RightText = "RIGHT";
final String resultText = LeftText + " " + RightText;
final SpannableString styledResultText = new SpannableString(resultText);
styledResultText.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), LeftText.length() + 1, LeftText.length() + 2 +RightText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(styledResultText);
But none of them seems to work.
To right align text in TextView in Kotlin Android, set android:textAlignment attribute with the value “viewEnd” in layout file, or programmatically set the textAlignment property of the TextView object with View.
To align text in TextView at the center vertically and horizontally we need to make use of gravity attribute. Example 1 : You can use center_vertical | center_horizontal value to set the text at the center of the TextView area.
Show activity on this post. Create a Custom View for Textview . Make the entry in the attrs. xml file and give an option to select Font as a list in custom TextView .
android:gravity="center" for text center in TextView. android:gravity="center_horizontal" inner text if you want horizontally centered. android:gravity="center_vertical" inner text if you want vertically centered. android:layout_centerInParent="true" if you want TextView in center position of parent view.
TextView resultTextView = new TextView(this);
final String resultText = LeftText + " " + RightText;
final SpannableString styledResultText = new SpannableString(resultText);
styledResultText.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE)
, LeftText.length() + 2
, LeftText.length() + 2 + RightText.length()
, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
resultTextView.setText(styledResultText);
Alignment.ALIGN_OPPOSITE is the equivalent for right side.
Alignment.ALIGN_NORMAL is the equivalent for left side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With