你如何得到一个TextView的文本是正当的(与文本flush在左边和右手边)?

我在这里找到了一个可能的解决方案,但它不起作用(即使您将vertical-center更改为center_vertical等)。


当前回答

@CommonsWare的答案是正确的。Android 8.0+确实支持“完全论证”(或简单的“论证”,因为它有时被含糊地提到)。

Android还支持“左/右文本对齐”。请参阅维基百科关于区分理由的文章。许多人认为“对齐”的概念包括完全对齐以及左/右文本对齐,这是他们在想要进行左/右文本对齐时最终搜索的内容。这个答案解释了如何实现左/右文本对齐。

可以实现左/右文本对齐(而不是问题所询问的完全对齐)。为了演示,我将使用一个基本的2列表单(标签在左列,文本字段在右列)作为示例。在本例中,左列标签中的文本将右对齐,因此它们将与右列中的文本字段齐平。

在XML布局中,你可以得到的TextView元素本身(左列)对齐到右边,通过添加以下属性在所有的TextView:

<TextView
   ...
   android:layout_gravity="center_vertical|end">
   ...
</TextView>

但是,如果文本换行到多行,文本仍将在TextView内保持左对齐。添加以下属性使实际文本在TextView内右对齐(不规则左对齐):

<TextView
   ...
   android:gravity="end">
   ...
</TextView>

重力属性指定如何对齐TextView内的文本layout_gravity指定如何对齐/布局TextView元素本身。

其他回答

我写了一个基于本地textview的小部件来做到这一点。

github

我认为有两种选择:

使用像Pango这样的东西,通过NDK专门处理这一点,并将文本渲染到OpenGL或其他表面。 使用Paint.measureText()和friends来获取单词的长度,并在自定义视图的Canvas上手动布局它们。

为了在android中证明文本,我使用了WebView

    setContentView(R.layout.main);

    WebView view = new WebView(this);
    view.setVerticalScrollBarEnabled(false);

    ((LinearLayout)findViewById(R.id.inset_web_view)).addView(view);

    view.loadData(getString(R.string.hello), "text/html; charset=utf-8", "utf-8");

和html。

<string name="hello">
<![CDATA[
<html>
 <head></head>
 <body style="text-align:justify;color:gray;background-color:black;">
  Lorem ipsum dolor sit amet, consectetur 
  adipiscing elit. Nunc pellentesque, urna
  nec hendrerit pellentesque, risus massa
 </body>
</html>
]]>
</string>

我还不能上传图片来证明它,但“它对我有用”。

虽然仍然不是完整的文本,你现在可以平衡行长度使用android:breakStrategy="balanced"从API 23起

http://developer.android.com/reference/android/widget/TextView.html#attr_android:breakStrategy

Simplay我们可以使用android: justify mode ="inter_word"

 <TextView
 android:justificationMode="inter_word"
 android:id="@+id/messageTv"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="@dimen/text_margin"
 android:paddingTop="15sp"
 android:textAppearance="@style/TextAppearance.Material3.TitleMedium" />