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

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


当前回答

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" />

其他回答

为了在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>

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

你可以在github中使用jusfiedtextview for Android项目。这是一个自定义视图,为您模拟正确的文本。它支持Android 2.0+和从右向左的语言。

@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元素本身。

请在8.0以下尝试此代码

<TextView 
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center_horizontal"
  android:gravity="center|start"/>

TextView在Android O提供了充分的理由(新的排版对齐)本身。 你只需要这样做:

科特林

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    textView.justificationMode = JUSTIFICATION_MODE_INTER_WORD
}

Java

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    textView.setJustificationMode(JUSTIFICATION_MODE_INTER_WORD);
}

XML

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:justificationMode="inter_word" />

默认值是jusication_mode_none (xml中的none)。