Is alignment working in HTML.fromHtml() in a TextView?
I tried
<div align="center"><p>Test</p></div>
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.
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));
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 :|
Alignment is not supported in HTML text in TextView.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With