簡體   English   中英

如何更改WebView的字體?^

[英]How can I change the font of a WebView?^

我想在Android Studio中的WebView中使用自定義字體

public void loadHTLMContentText(String text, WebView view) {

    String body;
    String head = "<head><style><style type=\"text/css\">@font-face {font-family: 'Standard';src: url('file:///android_asset/fonts/Standard.ttf')}body {font-family: Standard;text-align: justify;}</style></head>";
    if (text != null) {
        body = text;
    } else return;
    String htmlData = "<html>" + head + "<body>" + body + "</body></html>";


    view.loadData(htmlData, "text/html; charset=utf-8", "utf-8");
    view.setBackgroundColor(0x00000000);

}

我使用此代碼生成包含內容的HTLM文件。 路徑C:\\ Users \\ julia \\ AndroidStudioProjects \\ AktienApp \\ app \\ src \\ main \\ assets \\ fonts下的自定義字體ist。

然后我將內容加載到webview中

WebView text_1_a = (WebView) one.findViewById(R.id.text_slide_type_a_1);
        preparer.loadHTLMContentText(getString(R.string.Historie1), text_1_a);

但是它不會改變字體。 有人讓我失敗了嗎?

在這里,我制作了一個簡單的演示程序,用於在WebView中更改字體。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/imageLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="5dp">

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

    </LinearLayout>

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    WebView webview1;

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

        webview1 = (WebView) findViewById(R.id.webview1);
        webview1.loadUrl("file:///android_asset/demo.html");
    }
}

然后創建資產文件夾,並將一個HTML文件放入該文件夾中。

demo.html

<html>
<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
    <style type="text/css">
        @font-face { font-family: 'Persian'; src: url('file:///android_asset/fonts/Myfont.ttf'); }
        @font-face { font-family: 'Persian2'; src: url('file:///android_asset/fonts/newfont.ttf'); }
        body {font-family: 'Persian';}
        h1 {font-family: 'Persian2';}
    </style>
</head>
<body>
<h1>
    Welcome to CustomFont Demo
</h1>
    Testing text
</body>
</html>

在資源文件夾中,我再創建一個字體文件夾。 文件夾名稱是字體。

所以我使用字體uri像:file:///android_asset/fonts/Myfont.ttf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM