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

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


当前回答

我不认为Android支持完全的理由。

更新2018-01-01:Android 8.0+支持TextView对齐模式。

其他回答

我认为有两种选择:

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

FILL_HORIZONTAL等价于CENTER_HORIZONTAL。 你可以在textview的源代码中看到这个代码片段:

case Gravity.CENTER_HORIZONTAL:
case Gravity.FILL_HORIZONTAL:
    return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
            getCompoundPaddingLeft() - getCompoundPaddingRight())) /
            getHorizontalFadingEdgeLength();

更新

我们为此创建了一个简单的类。目前有两种方法可以达到你想要的效果。两者都不需要WEBVIEW和支持SPANNABLES。

图书馆:https://github.com/bluejamesbond/TextJustify-Android

支持:Android 2.0到5。X

设置

// Please visit Github for latest setup instructions.

截图

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)。

XML布局:声明WebView而不是TextView

<WebView
 android:id="@+id/textContent"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />

Java代码:设置文本数据到WebView

WebView view = (WebView) findViewById(R.id.textContent);
String text;
text = "<html><body><p align=\"justify\">";
text+= "This is the text will be justified when displayed!!!";
text+= "</p></body></html>";
view.loadData(text, "text/html", "utf-8");

这也许能解决你的问题。 它完全为我工作。