Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alignment in Html.fromHtml()

Tags:

android

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.

like image 855
Rene Avatar asked Oct 06 '10 16:10

Rene


5 Answers

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));
like image 170
himanshu Verma Avatar answered Oct 21 '22 18:10

himanshu Verma


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 :|

like image 21
Masoud Hashemian Avatar answered Oct 29 '22 19:10

Masoud Hashemian


Alignment is not supported in HTML text in TextView.

like image 16
Romain Guy Avatar answered Oct 29 '22 18:10

Romain Guy


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");
    }
}
like image 2
jsidera Avatar answered Oct 29 '22 19:10

jsidera


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.

like image 2
n8han Avatar answered Oct 29 '22 18:10

n8han