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

纵然是瞬间 提交于 2019-12-08 08:32:53

问题


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?


回答1:


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..




回答2:


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.



来源:https://stackoverflow.com/questions/14551759/partially-left-aligned-and-partially-right-aligned-text-in-a-textview-why-isnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!