【发布时间】:2010-10-06 16:56:17
【问题描述】:
在 TextView 的 HTML.fromHtml() 中对齐是否有效?
我试过了
<div align="center"><p>Test</p></div>
还有一些变体,包括将不带括号的对齐选项卡放在段落标记中,但没有一个起作用。文本始终保留。
感谢您的帮助!
你的。
【问题讨论】:
标签: android
在 TextView 的 HTML.fromHtml() 中对齐是否有效?
我试过了
<div align="center"><p>Test</p></div>
还有一些变体,包括将不带括号的对齐选项卡放在段落标记中,但没有一个起作用。文本始终保留。
感谢您的帮助!
你的。
【问题讨论】:
标签: android
TextView 中的 HTML 文本不支持对齐。
【讨论】:
要在 textview 中设置对齐方式,首先将 textview 宽度设置为 match_parent,然后在 HTML 标签中使用 text-align 选项。像这样:
<div style="text-align: center">this text should be in center of view</div>
更新: 此解决方案仅适用于 android 7 及更高版本:|
【讨论】:
val fixHtml = html.replace("<center>","<div style=\"text-align: center\">").replace("</center>","</div>")
虽然可以使用 webview 而不是 TextView 来使用对齐,并从放置在 assets 中的文件中加载 html:
public class ViewWeb extends Activity {
WebView webview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webview = (WebView) findViewById(R.id.webView1);
webview.loadUrl("file:///android_asset/index.html");
}
}
【讨论】:
对于 API 24 及更低版本,将 gravity 属性添加到 TextView 布局元素
android:gravity="center_horizontal"
对于 API 24 及更高版本,可以在 HTML 中使用 style。
String centeredHtml = "<div style=\"text-align: center\">" + myFormattedHtml + "</div>";
textView.setText(Html.fromHtml(centeredHtml));
但gravity 也支持至少 API 26。
【讨论】:
您不能在 HTML 文本中设置对齐方式,但可以使用 SpannableStringBuilder 代替。它很冗长,但可以完成工作。
例如
private Spanned getFormattedLabelText(String text, String subText) {
String fullText = String.format("%s\n%s", text, subText);
int fullTextLength = fullText.length();
int titleEnd = text.length();
SpannableStringBuilder s = new SpannableStringBuilder(fullText);
// Center align the text
AlignmentSpan alignmentSpan = new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER);
s.setSpan(alignmentSpan, 0, fullTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Make the title bold
s.setSpan(new StyleSpan(Typeface.BOLD), 0, titleEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //bold
// Make the subtext small
int smallTextSize = DisplayUtil.getPixels(TypedValue.COMPLEX_UNIT_SP, 10);
s.setSpan(new AbsoluteSizeSpan(smallTextSize), titleEnd + 1, fullTextLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //bold
return s;
}
然后像往常一样设置TextView文本:
myTextView.setText(getFormattedLabelText("Title", "Subtitle"));
【讨论】:
如果有人想用红色对齐居中的文本,那么可以使用下面的代码。
String centerNRed = "<div style='text-align:center' ><span style='color:red' >Hello World Its me.....</span></div>";
txt1.setText(Html.fromHtml(centerNRed));
【讨论】:
我相信在 TextView 中使用 Gravity 属性将文本居中更容易...
【讨论】: