Reputation: 123
I want to use a Custom Font in a WebView in android Studio
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);
}
I use this code to generate the HTLM file with the content. The custom font ist under the Path C:\Users\julia\AndroidStudioProjects\AktienApp\app\src\main\assets\fonts.
Then I load the content in the webview with this
WebView text_1_a = (WebView) one.findViewById(R.id.text_slide_type_a_1);
preparer.loadHTLMContentText(getString(R.string.Historie1), text_1_a);
But it doesn't change the font. Anybody got my failure?
Upvotes: 1
Views: 4730
Reputation: 46
Here I make one simple demo program for changing font in 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");
}
}
And I create assets folder and put one HTML file inside that folder.
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>
And inside assets folder, I create one more folder for font. folder name is fonts.
So I use font uri like : file:///android_asset/fonts/Myfont.ttf
Upvotes: 1