简体   繁体   中英

Partially left aligned and partially right aligned text in a TextView. Why isn't this working?

I'm having an issue with an textview in which i have some text that is supposed to be left aligned and some text that is supposed to be right aligned.

Here´s my attempt.

String LeftText = "LEFT";
String RightText = "RIGHT";


String resultText = LeftText + "  " + RightText;
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);

And here´s the xml for the textview.

<TextView
    android:id="@+id/titleBar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" 
/>

However this is not working. All the text is getting left aligned. What am I missing here?

You can use TabStopSpan to solve the problem pretty easily if rightText is doesn't need to be right justified against the edge.

final TextView tv = ...
int column = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                (float) 200.0, getResources().getDisplayMetrics());

SpannableStringBuilder textspan = new SpannableStringBuilder("Charges\nPrice\t$25.00\nShipping\t$155.08\nTax\t$5.11\n");
textspan.setSpan(new TabStopSpan.Standard(column), 0, textspan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(textspan);

if you want it moved near to the right edge of your text view you can set the Tab stop after layout using a global layout listener. Then you can use the width of the textview to set a tabstop near the edge.

If you want it right aligned you just need to make a class extending ReplacementSpan that will justify the text for you..

I've gone down this road myself...unfortunately, from my research I don't believe it's possible to have two alignment spans for a single line of text. You'll have to split it out into two different TextView objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM