Android TextView 对齐文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1292575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android TextView Justify Text
提问by
How do you get the text of a TextView
to be Justified (with text flush on the left- and right- hand sides)?
你如何让 a 的文本TextView
对齐(左右两边的文本齐平)?
I found a possible solution here, but it does not work (even if you change vertical-center to center_vertical, etc).
我在这里找到了一个可能的解决方案,但它不起作用(即使您将 vertical-center 更改为 center_vertical 等)。
采纳答案by CommonsWare
I do not believe Android supports full justification.
我不相信 Android 支持充分的理由。
UPDATE 2018-01-01: Android 8.0+ supports justification modes with TextView
.
更新 2018-01-01:Android 8.0+ 支持带有TextView
.
回答by plainjimbo
The @CommonsWare answer is correct. Android 8.0+ does support "Full Justification" (or simply "Justification", as it is sometimes ambiguously referred to).
@CommonsWare 答案是正确的。Android 8.0+ 确实支持“完全理由”(或简称为“理由”,因为有时会含糊其辞)。
Android also supports "Flush Left/Right Text Alignment". See the wikipedia article on Justificationfor the distinction. Many people consider the concept of 'justification' to encompass full-justification as well as left/right text alignment, which is what they end up searching for when they want to do left/right text alignment. This answer explains how to achieve the left/right text alignment.
Android 还支持“Flush Left/Right Text Alignment”。请参阅维基百科关于理由的文章以了解区别。许多人认为“对齐”的概念包含完全对齐以及左/右文本对齐,这是他们想要进行左/右文本对齐时最终搜索的内容。这个答案解释了如何实现左/右文本对齐。
It is possible to achieve Flush Left/Right Text Alignment (as opposed to Full Justification, as the question is asking about). To demonstrate I will be using a basic 2-column form (labels in the left column and text fields in the right column) as an example. In this example the text in the labels in the left column will be right-aligned so they appear flush up against their text fields in the right column.
可以实现 Flush Left/Right 文本对齐(与问题所问的完全对齐相反)。为了演示,我将使用一个基本的 2 列表单(左列中的标签和右列中的文本字段)作为示例。在此示例中,左列标签中的文本将右对齐,因此它们看起来与右列中的文本字段齐平。
In the XML layout you can get the TextView elements themselves (the left column) to align to the right by adding the following attribute inside all of the TextViews:
在 XML 布局中,您可以通过在所有 TextView 中添加以下属性来使 TextView 元素本身(左列)向右对齐:
<TextView
...
android:layout_gravity="center_vertical|end">
...
</TextView>
However, if the text wraps to multiple lines, the text would still be flush left aligned inside the TextView. Adding the following attribute makes the actual text flush right aligned (ragged left) inside the TextView:
但是,如果文本换行到多行,文本仍将在 TextView 内齐平左对齐。添加以下属性使实际文本在 TextView 中右对齐(左对齐):
<TextView
...
android:gravity="end">
...
</TextView>
So the gravityattribute specifies how to align the text inside the TextView layout_gravityspecifies how to align/layout the TextView element itself.
因此,gravity属性指定如何对齐 TextView 内部的文本layout_gravity指定如何对齐/布局 TextView 元素本身。
回答by Konrad Nowicki
To justify text in android I used WebView
为了在 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");
and html.
和 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>
I can't yet upload images to prove it but "it works for me".
我还不能上传图片来证明这一点,但“它对我有用”。
回答by Mathew Kurian
UPDATED
更新
We have created a simple class for this. There are currently two methods to achieve what you are looking for. Both require NO WEBVIEWand SUPPORTS SPANNABLES.
我们为此创建了一个简单的类。目前有两种方法可以实现您的需求。两者都不需要WEBVIEW和SUPPORTS SPANNABLES。
LIBRARY: https://github.com/bluejamesbond/TextJustify-Android
图书馆:https: //github.com/bluejamesbond/TextJustify-Android
SUPPORTS: Android 2.0 to 5.X
支持:Android 2.0 到 5.X
SETUP
设置
// Please visit Github for latest setup instructions.
SCREENSHOT
截屏
回答by Jaydipsinh Zala
TextView
in Android O
offers full justification (new typographic alignment) itself.
TextView
inAndroid O
提供了充分的理由(新的排版对齐)本身。
You just need to do this:
你只需要这样做:
Kotlin
科特林
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);
}
default is JUSTIFICATION_MODE_NONE
.
默认为JUSTIFICATION_MODE_NONE
.
回答by Saeed Zarinfam
You can use JustifiedTextView for Androidproject in github. this is a custom view that simulate justified text for you. It support Android 2.0+ and right to left languages.
您可以在 github 中为 Android项目使用JustifiedTextView。这是一个为您模拟对齐文本的自定义视图。它支持 Android 2.0+ 和从右到左的语言。
回答by Frank Cheng
回答by twiceYuan
I found a way to solve this problem, but this may not be very grace, but the effect is not bad.
我找到了解决这个问题的方法,但这可能不是很优雅,但效果还不错。
Its principle is to replace the spaces of each line to the fixed-width ImageSpan (the color is transparent).
其原理是将每一行的空格替换为固定宽度的ImageSpan(颜色为透明)。
public static void justify(final TextView textView) {
final AtomicBoolean isJustify = new AtomicBoolean(false);
final String textString = textView.getText().toString();
final TextPaint textPaint = textView.getPaint();
final SpannableStringBuilder builder = new SpannableStringBuilder();
textView.post(new Runnable() {
@Override
public void run() {
if (!isJustify.get()) {
final int lineCount = textView.getLineCount();
final int textViewWidth = textView.getWidth();
for (int i = 0; i < lineCount; i++) {
int lineStart = textView.getLayout().getLineStart(i);
int lineEnd = textView.getLayout().getLineEnd(i);
String lineString = textString.substring(lineStart, lineEnd);
if (i == lineCount - 1) {
builder.append(new SpannableString(lineString));
break;
}
String trimSpaceText = lineString.trim();
String removeSpaceText = lineString.replaceAll(" ", "");
float removeSpaceWidth = textPaint.measureText(removeSpaceText);
float spaceCount = trimSpaceText.length() - removeSpaceText.length();
float eachSpaceWidth = (textViewWidth - removeSpaceWidth) / spaceCount;
SpannableString spannableString = new SpannableString(lineString);
for (int j = 0; j < trimSpaceText.length(); j++) {
char c = trimSpaceText.charAt(j);
if (c == ' ') {
Drawable drawable = new ColorDrawable(0x00ffffff);
drawable.setBounds(0, 0, (int) eachSpaceWidth, 0);
ImageSpan span = new ImageSpan(drawable);
spannableString.setSpan(span, j, j + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
builder.append(spannableString);
}
textView.setText(builder);
isJustify.set(true);
}
}
});
}
I put the code on GitHub: https://github.com/twiceyuan/TextJustification
我把代码放在GitHub上:https: //github.com/twiceyuan/TextJustification
Overview:
概述:
回答by twiceYuan
XML Layout: declare WebView instead of TextView
XML 布局:声明 WebView 而不是 TextView
<WebView
android:id="@+id/textContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
Java code: set text data to WebView
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");
This may Solve your problem. Its Fully worked for me.
这可能会解决您的问题。它完全为我工作。
回答by Benoit Duffez
Here's how I did it, I think the most elegant way I could. With this solution, the only things you need to do in your layouts are:
这是我如何做到的,我认为这是我能做到的最优雅的方式。使用此解决方案,您在布局中唯一需要做的事情是:
- add an additional
xmlns
declaration - change your
TextView
s source text namespace from android to your new namespace - replace your
TextView
s withx.y.z.JustifiedTextView
- 添加额外的
xmlns
声明 - 将您
TextView
的源文本命名空间从 android更改为新命名空间 - 将你的
TextView
s替换为x.y.z.JustifiedTextView
Here's the code. Works perfectly fine on my phones (Galaxy Nexus Android 4.0.2, Galaxy Teos Android 2.1). Feel free, of course, to replace my package name with yours.
这是代码。在我的手机上完美运行(Galaxy Nexus Android 4.0.2、Galaxy Teos Android 2.1)。当然,可以随意用你的包名替换我的包名。
/assets/justified_textview.css:
/assets/justified_textview.css:
body {
font-size: 1.0em;
color: rgb(180,180,180);
text-align: justify;
}
@media screen and (-webkit-device-pixel-ratio: 1.5) {
/* CSS for high-density screens */
body {
font-size: 1.05em;
}
}
@media screen and (-webkit-device-pixel-ratio: 2.0) {
/* CSS for extra high-density screens */
body {
font-size: 1.1em;
}
}
/res/values/attrs.xml:
/res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="JustifiedTextView">
<attr name="text" format="reference" />
</declare-styleable>
</resources>
/res/layout/test.xml:
/res/layout/test.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/net.bicou.myapp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<net.bicou.myapp.widget.JustifiedTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
myapp:text="@string/surv1_1" />
</LinearLayout>
</ScrollView>
/src/net/bicou/myapp/widget/JustifiedTextView.java:
/src/net/bicou/myapp/widget/JustifiedTextView.java:
package net.bicou.myapp.widget;
import net.bicou.myapp.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebView;
public class JustifiedTextView extends WebView {
public JustifiedTextView(final Context context) {
this(context, null, 0);
}
public JustifiedTextView(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public JustifiedTextView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
if (attrs != null) {
final TypedValue tv = new TypedValue();
final TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.JustifiedTextView, defStyle, 0);
if (ta != null) {
ta.getValue(R.styleable.JustifiedTextView_text, tv);
if (tv.resourceId > 0) {
final String text = context.getString(tv.resourceId).replace("\n", "<br />");
loadDataWithBaseURL("file:///android_asset/",
"<html><head>" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"justified_textview.css\" />" +
"</head><body>" + text + "</body></html>",
"text/html", "UTF8", null);
setTransparentBackground();
}
}
}
}
public void setTransparentBackground() {
try {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
} catch (final NoSuchMethodError e) {
}
setBackgroundColor(Color.TRANSPARENT);
setBackgroundDrawable(null);
setBackgroundResource(0);
}
}
We need to set the rendering to software in order to get transparent background on Android 3+. Hence the try-catch for older versions of Android.
我们需要将渲染设置为软件才能在 Android 3+ 上获得透明背景。因此,对旧版本的 Android 进行了尝试。
Hope this helps!
希望这可以帮助!
PS: please not that it might be useful to add this to your whole activity on Android 3+ in order to get the expected behavior:android:hardwareAccelerated="false"
PS:请不要将其添加到您在 Android 3+ 上的整个活动中以获得预期行为可能有用:android:hardwareAccelerated="false"