Multiple alignment in TextView?
Asked Answered
H

3

22

I have a TextView like below. I used this code to set gray color for a part of the text.

// Prepare result text.
final String resultText = text + "\n\n" + dictionaryName;
final SpannableString styledResultText = new SpannableString(resultText);
styledResultText.setSpan(new ForegroundColorSpan(Color.GRAY), text.length() + 2, text.length() + 2 + dictionaryName.length(), 0);
resultTextView.setText(styledResultText);

Now I want to set align for it. How to do? Android doesn't have any span class for alignment. I can't find out anything like "AlignmentSpan".

enter image description here

Heder answered 11/7, 2011 at 17:32 Comment(0)
F
52

Though its really late to answer, I assume that it might help someone at least. Add this to your code.

styledResultText.setSpan(
    new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), 
    text.length() + 2,
    text.length() + 2 + dictionaryName.length(), 
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);

Alignment.ALIGN_OPPOSITE is the equivalent for right side.

Alignment.ALIGN_NORMAL is the equivalent for left side.

Note: This only works when there is at least 1 new-line character (\n) between the left & right-aligned text.

Flimflam answered 23/7, 2012 at 12:17 Comment(5)
This definitely should be the accepted answer! This also works for centering text via Alignment.ALIGN_CENTER.Aindrea
For some reason I can't get this to work in my TextView. All the lines have the same alignment.Himyarite
Its not working. I have \n as well in middle of stringTimmie
How to it in one line?Cornerstone
Not working in one line sentence. Example: "Start Year 2016". "2016" won't alight to right.Balfour
G
2

I think you should split the text into more than 1 string, put them into separated textview then align one by one.

Hope this helps.

Gramps answered 12/12, 2012 at 16:14 Comment(0)
R
0

If the resultText is always going to be right-aligned, add the gravity="right" attribute to your resultTextView instead of trying to right-align the text with styled spannable strings. This is assuming the grey text is within a separate TextView than your main text.

In xml for the result (grey) text:

<TextView android:id="@+id/resultTextView" 
    android:gravity="right" 
    android:layout_width="fill_parent" />
Replete answered 11/7, 2011 at 17:39 Comment(2)
No, I mean the black text left aligned and the gray text right aligned. I call it "multiple alignment". :)Heder
You would need to separate the black text from the result text (have 2 separate textviews).Replete

© 2022 - 2024 — McMap. All rights reserved.