你如何得到一个TextView的文本是正当的(与文本flush在左边和右手边)?
我在这里找到了一个可能的解决方案,但它不起作用(即使您将vertical-center更改为center_vertical等)。
你如何得到一个TextView的文本是正当的(与文本flush在左边和右手边)?
我在这里找到了一个可能的解决方案,但它不起作用(即使您将vertical-center更改为center_vertical等)。
当前回答
请在8.0以下尝试此代码
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center|start"/>
其他回答
FILL_HORIZONTAL等价于CENTER_HORIZONTAL。 你可以在textview的源代码中看到这个代码片段:
case Gravity.CENTER_HORIZONTAL:
case Gravity.FILL_HORIZONTAL:
return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
getCompoundPaddingLeft() - getCompoundPaddingRight())) /
getHorizontalFadingEdgeLength();
我认为有两种选择:
使用像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>
我还不能上传图片来证明它,但“它对我有用”。
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文件中使用此属性即可
android:justificationMode="inter_word"