简体   繁体   中英

How to text-justify in android textview and at the same time use custom font style?

public class FontTextView extends TextView {

    public FontTextView(Context context) {
        super(context);
        Typeface face = Typeface.createFromAsset(context.getAssets(),"palatino.ttf");
        this.setTypeface(face);
    }

    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Typeface face = Typeface.createFromAsset(context.getAssets(),"palatino.ttf");
        this.setTypeface(face);
    }

    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        Typeface face = Typeface.createFromAsset(context.getAssets(),"palatino.ttf");
        this.setTypeface(face);
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

}

I have a textview like this to using the custom font. The problem is , I would to make it justify as well. I have tried using the html code like this :

testText.setText(Html.fromHtml("<html><head><div class=\"haodi_jianjie\";style=\"text-align:justify;text-justify:distribute-all-lines;color:white;background-color:black;\">asdsadsadsadsadsadsadsafsdvvbcvbcvb dfsdfsdgfgdfg  gdfghththgfhgfhgfhgfhfghgfhgfhgf sdfsdfsdfsdfsdfsdfsfwqewqewq</div></head></html>"));

but it doesn't work. I prefer not using web-view as the transparent background is buggy for the webview but I need the background to be transparent.

Thanks a lot.

Full left and right justification is not supported by the Android TextView.

Your only option is to switch to a WebView or use some kind of custom TextView. I do not recommend the custom TextView because it would mean you would have to rewrite it completely down to the core. I suggest you switch to an WebView instead or use a library like this one: https://github.com/bluejamesbond/TextJustify-Android


About html in a TextView:

Android TextView does not support all html tags, only a few basic tags are supported. CSS is not supported.

Valid html tags:

<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font size="..." color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>

Source: http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html

We have created a simple class for this. Requires NO WEBVIEW and SUPPORTS SPANNABLES . You can also provide your own custom fonts!

LIBRARY : https://github.com/bluejamesbond/TextJustify-Android

图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM