Is alignment working in HTML.fromHtml() in a TextView?
I tried
<div align="center"><p>Test</p></div>
开发者_C百科
and some variaties of this, including putting the alignment tabs without parenthesis to the paragraph tag, but none worked. The text is always left.
Thanks for any help!
Yours.
Alignment is not supported in HTML text in TextView.
To set alignment in textview first set textview width to match_parent and then use text-align option in your HTML tag. something like this:
<div style="text-align: center">this text should be in center of view</div>
Update: This solution just work in android 7 and above :|
Although it is possible to use alignment using a webview instead of a TextView, and loading the html from a file placed in assets:
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");
}
}
For API 24 and below, add a gravity
attribute to the TextView
layout element
android:gravity="center_horizontal"
For API 24 and above, can use a style
within the HTML.
String centeredHtml = "<div style=\"text-align: center\">" + myFormattedHtml + "</div>";
textView.setText(Html.fromHtml(centeredHtml));
But gravity
is also supported up to at least API 26.
You cannot set alignment in HTML text but you can use a SpannableStringBuilder instead. It's verbose but it gets the job done.
E.g.
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;
}
Then set the TextView text as usual:
myTextView.setText(getFormattedLabelText("Title", "Subtitle"));
If someone wants to align text in center with color red then one may use code below.
String centerNRed = "<div style='text-align:center' ><span style='color:red' >Hello World Its me.....</span></div>";
txt1.setText(Html.fromHtml(centerNRed));
I believe is more easy use the property Gravity in a TextView for center the text...
精彩评论