Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中實現文本兩端對齊:借 WebView 完成排版

編輯:關於 Android 程式設計

Android 原生的 TextView 對「兩端對齊」(justify)支持得並不友好,行尾不齊在中文正文裡尤其明顯。一個取巧又穩妥的做法是把內容交給 WebView 渲染,用 CSS 的 text-align:justify 來實現。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String htmlText = "<html><body><div style=\"text-align:justify\">%s</div></body></html>";
        String myData = "Hello World! This tutorial is to show demo of "
                + "displaying text with justify alignment in WebView.";

        WebView webView = (WebView) findViewById(R.id.webView1);
        webView.loadData(String.format(htmlText, myData), "text/html", "utf-8");
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

要點:loadData 的第二個參數必須寫 "text/html",第三個是編碼,寫 "utf-8" 才能避免中文亂碼。此外 CSS 裡加 text-indent:2em 還能順手實現首行縮排,配合 line-height 調整行距,排版效果會更接近印刷體。

感謝閱讀,希望能幫助到大家。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved