Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a certain part of a android-textview align to the right

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.

like image 726
user1991905 Avatar asked Jan 25 '13 11:01

user1991905


People also ask

How do you right align text on android?

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.

How do I align text in text 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.

How do you customize TextView?

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 .

How do you change the text in the middle of 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.


1 Answers

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.

like image 70
Vikalp Patel Avatar answered Oct 07 '22 12:10

Vikalp Patel