config WebView using WebSettings - Android User Interface

Android examples for User Interface:WebView

Description

config WebView using WebSettings

Demo Code


import android.annotation.SuppressLint;
import android.content.Context;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class Main{
    public static void configWebView(WebView wb, Context context) {
        configWebView(wb, context, true);
    }/*from  w  w w  . ja  v a  2 s  .c o m*/
    @SuppressWarnings("deprecation")
    @SuppressLint({ "SetJavaScriptEnabled" })
    public static void configWebView(final WebView wb, Context context,
            boolean useMyOwnClient) {
        WebSettings ws = wb.getSettings();
        ws.setJavaScriptEnabled(true);

        ws.setDomStorageEnabled(true);

        ws.setSavePassword(false);

        ws.setSupportZoom(false);

        ws.setBuiltInZoomControls(false);

        ws.setUseWideViewPort(true);

        ws.setDefaultTextEncodingName("utf-8");

        ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

        ws.setLoadWithOverviewMode(true);

        // region Cache
        ws.setDatabaseEnabled(true);
        ws.setAppCacheEnabled(true);
        ws.setAllowFileAccess(true);
        ws.setDatabasePath(context.getCacheDir().toString());
        ws.setAppCachePath(context.getCacheDir().toString());
        ws.setAppCacheMaxSize(1024 * 1024 * 8);
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);
        //ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        // endregion

        if (useMyOwnClient) {
            wb.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view,
                        String url) {
                    view.loadUrl(url);
                    return true;
                }
            });

            wb.setWebChromeClient(new WebChromeClient());

            wb.setOnKeyListener(new OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (event.getAction() == 1 && keyCode == 4
                            && wb.canGoBack()) {
                        wb.goBack();
                        return true;
                    } else {
                        return false;
                    }
                }
            });
        }

        wb.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return true;
            }
        });
    }
}

Related Tutorials