如何在Android上的WebView上正确对齐文本?

时间:2016-12-24 16:36:32

标签: android textview android-webview

我想证明TextView的文字是合理的,但我无法在TextView上找到任何方法,因此我创建了WebView

WebView上设置文字的代码如下:

WebView webview = (WebView) view.findViewById(R.id.webview);
webview.loadData(getString(R.string.webview), "text/html; charset=utf-8", "utf-8");
webview.setBackgroundColor(Color.TRANSPARENT);

效果很好,文字显示合理(因为我创建了一个body标记{。}}。

问题在于,当我将文本加载到style="text-align:justify;时,它会花费几秒钟来收取文本费用。因此,在文本出现之前显示其余的布局,产生奇怪的视觉效果。

我试图等到WebView完全加载(How to listen for a WebView finishing loading a URL?),但文本永远不会显示。这是我目前的代码:

WebView

那么,如何在布局的其余部分同时显示合理的文本?

提前致谢!

1 个答案:

答案 0 :(得分:0)

这是图片:enter image description here

这是我在项目中使用的代码 它不需要加载

 void initVebView(WebView wvContent_Detail, String body) {
        String HTML1 = "<html><head><style type=\"text/css\">@font-face      {font-family: MyFont;src: url(\"file:///android_asset/%s\")}body {font-family: MyFont;font-size: medium;text-align: justify; line-height: %spx;}</style></head><body dir='rtl'>";
    String HTML2 = "</body></html>";
    String HTML3 = "<span style=\"font-weight:bold\">%s<br/><br/>%s</span>";

    String HTML4 = "<style>img{display: inline;height: auto;max-width: 100%;</style>";

    String str = String.format(HTML1, "IRANSansMobile_UltraLight.ttf", 25);


    String content = body.replace("text-align:", "");
    content = content.replace("font-family:", "");
    content = content.replace("line-height:", "");
    content = content.replace("dir=", "");
    content = content.replace("width=", "width=\"100%;\"");

    String myHtmlString = str + content + HTML2;

    wvContent_Detail.loadDataWithBaseURL(null, HTML4 + myHtmlString, "text/html", "UTF-8", null);

    WebSettings webSettings = wvContent_Detail.getSettings();
    webSettings.setDefaultFontSize(20);
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
}

这是xml:

  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   tools:context="ir.tenthwindow.BaseModule.ui.FragmentVideo">

   <ScrollView
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <WebView 
           android:id="@+id/webview_product_details"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_marginLeft="10dp"
           android:layout_marginRight="10dp" />
   </ScrollView>
  </FrameLayout>

您可以使用您的字体。 希望这有帮助。