开发者

How to change the FontSize in an Android WebView?

How can you manually change the font size of a webview? e.g.开发者_如何学运维 When the page loads up in the webview the font size is like 24pt. and way too large for my android's screen. I've looked into the "websettings" but it seems that the two are not related.

Thanks


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜