简体   繁体   English

TextView中部分左对齐和部分右对齐的文本。 为什么这不起作用?

[英]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. 我遇到了一个textview的问题,其中我有一些应该左对齐的文本和一些应该正确对齐的文本。

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的xml。

<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. 如果rightText不需要对边缘进行右对齐,则可以使用TabStopSpan轻松解决问题。

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. 如果您希望它移动到文本视图的右边缘附近,则可以使用全局布局侦听器在布局后设置Tab停止。 Then you can use the width of the textview to set a tabstop near the edge. 然后,您可以使用textview的宽度在边缘附近设置一个tabstop。

If you want it right aligned you just need to make a class extending ReplacementSpan that will justify the text for you.. 如果你想要正确对齐你只需要创建一个扩展ReplacementSpan的类,它将为你证明文本的合理性。

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. 您必须将其拆分为两个不同的TextView对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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