How to change the FontSize in an Android WebView?

为君一笑 提交于 2019-11-26 17:29:57
Scott

I finally found it:-

WebSettings webSettings = webView.getSettings();

either setTextSize or

webSettings.setTextSize(WebSettings.TextSize.SMALLEST);

This one works too:-

webSettings.setDefaultFontSize(10);

It seems that nowadays prefered way, ie not depreciated is to change text zoom, like this:

WebSettings settings = mWebView.getSettings();
settings.setTextZoom(90); // where 90 is 90%; default value is ... 100

This is what I use when I want to enable the user to change the text size / zoom in a WebView:

private WebView mWebView;

// init web view and stuff like that ...


private void textSmaller() {

    WebSettings settings = mWebView.getSettings();
    settings.setTextZoom(settings.getTextZoom() - 10);
}

private void textBigger() {

    WebSettings settings = mWebView.getSettings();
    settings.setTextZoom(settings.getTextZoom() + 10);
}

On Actionbar Item click, I call either textSmaller() or textBigger() to change the text size.

I use Javascript to do these kind of things because it practically always works. Even if there are CSS files used in your HTML

mWebView.loadUrl("javascript:(document.body.style.backgroundColor ='red');");
mWebView.loadUrl("javascript:(document.body.style.color ='yellow');");
mWebView.loadUrl("javascript:(document.body.style.fontSize ='20pt');");

ofcourse you need to alter the sizes and colors to the ones you need

If you want to increase or decrease font Size of WebView dynamycally than use these lines of code:

WebView mWebView;
int fontSize;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = findViewById(R.id.webview);
    mWebView.loadUrl("file:///android_asset/sample.html");
    // enable / disable javascript
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setSupportZoom(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setDisplayZoomControls(true);
    fontSize = mWebView.getSettings().getDefaultFontSize();
}
 private void fontSizePlus() {
    fontSize++;
    this.changeFontSize(fontSize);
}

private void fontSizeMinus() {
    fontSize--;
    this.changeFontSize(fontSize);
}

private void changeFontSize(int value) {
    mWebView.getSettings().setDefaultFontSize(value);
}

public void Inc(View view) {
    fontSizePlus();
}

public void Dec(View view) {
    fontSizeMinus();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!