Example usage for android.webkit WebView setWebViewClient

List of usage examples for android.webkit WebView setWebViewClient

Introduction

In this page you can find the example usage for android.webkit WebView setWebViewClient.

Prototype

public void setWebViewClient(WebViewClient client) 

Source Link

Document

Sets the WebViewClient that will receive various notifications and requests.

Usage

From source file:com.androzic.waypoint.WaypointInfo.java

@SuppressLint("NewApi")
private void updateWaypointInfo(double lat, double lon) {
    Androzic application = Androzic.getApplication();
    Activity activity = getActivity();//from   w ww  .  jav  a 2 s .c o m
    Dialog dialog = getDialog();
    View view = getView();

    WebView description = (WebView) view.findViewById(R.id.description);

    if ("".equals(waypoint.description)) {
        description.setVisibility(View.GONE);
    } else {
        String descriptionHtml;
        try {
            TypedValue tv = new TypedValue();
            Theme theme = activity.getTheme();
            Resources resources = getResources();
            theme.resolveAttribute(android.R.attr.textColorSecondary, tv, true);
            int secondaryColor = resources.getColor(tv.resourceId);
            String css = String.format(
                    "<style type=\"text/css\">html,body{margin:0;background:transparent} *{color:#%06X}</style>\n",
                    (secondaryColor & 0x00FFFFFF));
            descriptionHtml = css + waypoint.description;
            description.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    view.setBackgroundColor(Color.TRANSPARENT);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
                }
            });
            description.setBackgroundColor(Color.TRANSPARENT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                description.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
        } catch (Resources.NotFoundException e) {
            description.setBackgroundColor(Color.LTGRAY);
            descriptionHtml = waypoint.description;
        }

        WebSettings settings = description.getSettings();
        settings.setDefaultTextEncodingName("utf-8");
        settings.setAllowFileAccess(true);
        Uri baseUrl = Uri.fromFile(new File(application.dataPath));
        description.loadDataWithBaseURL(baseUrl.toString() + "/", descriptionHtml, "text/html", "utf-8", null);
    }

    String coords = StringFormatter.coordinates(" ", waypoint.latitude, waypoint.longitude);
    ((TextView) view.findViewById(R.id.coordinates)).setText(coords);

    if (waypoint.altitude != Integer.MIN_VALUE) {
        ((TextView) view.findViewById(R.id.altitude)).setText(StringFormatter.elevationH(waypoint.altitude));
    }

    double dist = Geo.distance(lat, lon, waypoint.latitude, waypoint.longitude);
    double bearing = Geo.bearing(lat, lon, waypoint.latitude, waypoint.longitude);
    bearing = application.fixDeclination(bearing);
    String distance = StringFormatter.distanceH(dist) + " " + StringFormatter.angleH(bearing);
    ((TextView) view.findViewById(R.id.distance)).setText(distance);

    if (waypoint.date != null)
        ((TextView) view.findViewById(R.id.date))
                .setText(DateFormat.getDateFormat(activity).format(waypoint.date) + " "
                        + DateFormat.getTimeFormat(activity).format(waypoint.date));
    else
        ((TextView) view.findViewById(R.id.date)).setVisibility(View.GONE);

    dialog.setTitle(waypoint.name);
}

From source file:com.androzic.waypoint.WaypointDetails.java

@SuppressLint("NewApi")
private void updateWaypointDetails(double lat, double lon) {
    Androzic application = Androzic.getApplication();
    AppCompatActivity activity = (AppCompatActivity) getActivity();

    activity.getSupportActionBar().setTitle(waypoint.name);

    View view = getView();//from w  w  w.j a  v a2s.c o  m

    final TextView coordsView = (TextView) view.findViewById(R.id.coordinates);
    coordsView.requestFocus();
    coordsView.setTag(Integer.valueOf(StringFormatter.coordinateFormat));
    coordsView.setText(StringFormatter.coordinates(" ", waypoint.latitude, waypoint.longitude));
    coordsView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int format = ((Integer) coordsView.getTag()).intValue() + 1;
            if (format == 5)
                format = 0;
            coordsView.setText(StringFormatter.coordinates(format, " ", waypoint.latitude, waypoint.longitude));
            coordsView.setTag(Integer.valueOf(format));
        }
    });

    if (waypoint.altitude != Integer.MIN_VALUE) {
        ((TextView) view.findViewById(R.id.altitude))
                .setText("\u2336 " + StringFormatter.elevationH(waypoint.altitude));
        view.findViewById(R.id.altitude).setVisibility(View.VISIBLE);
    } else {
        view.findViewById(R.id.altitude).setVisibility(View.GONE);
    }

    if (waypoint.proximity > 0) {
        ((TextView) view.findViewById(R.id.proximity))
                .setText("~ " + StringFormatter.distanceH(waypoint.proximity));
        view.findViewById(R.id.proximity).setVisibility(View.VISIBLE);
    } else {
        view.findViewById(R.id.proximity).setVisibility(View.GONE);
    }

    double dist = Geo.distance(lat, lon, waypoint.latitude, waypoint.longitude);
    double bearing = Geo.bearing(lat, lon, waypoint.latitude, waypoint.longitude);
    bearing = application.fixDeclination(bearing);
    String distance = StringFormatter.distanceH(dist) + " " + StringFormatter.angleH(bearing);
    ((TextView) view.findViewById(R.id.distance)).setText(distance);

    ((TextView) view.findViewById(R.id.waypointset)).setText(waypoint.set.name);

    if (waypoint.date != null) {
        view.findViewById(R.id.date_row).setVisibility(View.VISIBLE);
        ((TextView) view.findViewById(R.id.date))
                .setText(DateFormat.getDateFormat(activity).format(waypoint.date) + " "
                        + DateFormat.getTimeFormat(activity).format(waypoint.date));
    } else {
        view.findViewById(R.id.date_row).setVisibility(View.GONE);
    }

    if ("".equals(waypoint.description)) {
        view.findViewById(R.id.description_row).setVisibility(View.GONE);
    } else {
        WebView description = (WebView) view.findViewById(R.id.description);
        String descriptionHtml;
        try {
            TypedValue tv = new TypedValue();
            Theme theme = activity.getTheme();
            Resources resources = getResources();
            theme.resolveAttribute(android.R.attr.textColorPrimary, tv, true);
            int secondaryColor = resources.getColor(tv.resourceId);
            String css = String.format(
                    "<style type=\"text/css\">html,body{margin:0;background:transparent} *{color:#%06X}</style>\n",
                    (secondaryColor & 0x00FFFFFF));
            descriptionHtml = css + waypoint.description;
            description.setWebViewClient(new WebViewClient() {
                @SuppressLint("NewApi")
                @Override
                public void onPageFinished(WebView view, String url) {
                    view.setBackgroundColor(Color.TRANSPARENT);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
                }
            });
            description.setBackgroundColor(Color.TRANSPARENT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                description.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
        } catch (Resources.NotFoundException e) {
            description.setBackgroundColor(Color.LTGRAY);
            descriptionHtml = waypoint.description;
        }

        WebSettings settings = description.getSettings();
        settings.setDefaultTextEncodingName("utf-8");
        settings.setAllowFileAccess(true);
        Uri baseUrl = Uri.fromFile(new File(application.dataPath));
        description.loadDataWithBaseURL(baseUrl.toString() + "/", descriptionHtml, "text/html", "utf-8", null);
        view.findViewById(R.id.description_row).setVisibility(View.VISIBLE);
    }
}

From source file:it.angrydroids.epub3reader.BookView.java

@Override
public void onActivityCreated(Bundle saved) {
    super.onActivityCreated(saved);
    view = (WebView) getView().findViewById(R.id.Viewport);

    // enable JavaScript for cool things to happen!
    view.getSettings().setJavaScriptEnabled(true);

    // ----- SWIPE PAGE
    view.setOnTouchListener(new OnTouchListener() {
        @Override/*from ww  w. j a  v a  2s. co  m*/
        public boolean onTouch(View v, MotionEvent event) {

            if (state == ViewStateEnum.books)
                swipePage(v, event, 0);

            WebView view = (WebView) v;
            return view.onTouchEvent(event);
        }
    });

    // ----- NOTE & LINK
    view.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Message msg = new Message();
            msg.setTarget(new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    String url = msg.getData().getString(getString(R.string.url));
                    if (url != null)
                        navigator.setNote(url, index);
                }
            });
            view.requestFocusNodeHref(msg);

            return false;
        }
    });

    view.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                navigator.setBookPage(url, index);
            } catch (Exception e) {
                errorMessage(getString(R.string.error_LoadPage));
            }
            return true;
        }
    });

    view.addJavascriptInterface(new MyJavaScriptInterface(), "INTERFACE");
    view.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            view.loadUrl(
                    "javascript:window.INTERFACE.processContent(document.getElementsByTagName('body')[0].innerText);");
        }
    });

    PreButton = (Button) getView().findViewById(R.id.btn_prev_chunk);
    TopButton = (Button) getView().findViewById(R.id.btn_display_from_top);
    FwdButton = (Button) getView().findViewById(R.id.btn_fwd_chunk);

    PreButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BtnPrevChunkOnClickListner(v);
        }
    });

    TopButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BtnDisplayTopOnClickListner(v);
        }
    });

    FwdButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BtnFwdChunkOnClickListner(v);
        }
    });
    loadPage(viewedPage);
}

From source file:com.rsltc.profiledata.main.MainActivity.java

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

    Button loginButton = (Button) findViewById(R.id.button);
    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override/*from  w ww .j a  v a 2  s  . c om*/
        public void onClick(View v) {
            try {
                AlertDialog.Builder alert = new AlertDialog.Builder(thisActivity);
                alert.setTitle("Title here");

                StringBuilder query = new StringBuilder();

                query.append("redirect_uri=" + URLEncoder.encode(redirectUri, "utf-8"));
                query.append("&client_id=" + URLEncoder.encode(clientId, "utf-8"));
                query.append("&scope=" + URLEncoder.encode(scopes, "utf-8"));

                query.append("&response_type=code");
                URI uri = new URI("https://login.live.com/oauth20_authorize.srf?" + query.toString());

                URL url = uri.toURL();

                final WebView wv = new WebView(thisActivity);

                WebSettings webSettings = wv.getSettings();
                webSettings.setJavaScriptEnabled(true);
                wv.loadUrl(url.toString());
                wv.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String location) {
                        Log.e(TAG, location);
                        // TODO: extract to method
                        try {
                            URL url = new URL(location);

                            if (url.getPath().equalsIgnoreCase("/oauth20_desktop.srf")) {
                                System.out.println("Dit werkt al!");
                                System.out.println(url.getQuery());
                                Map<String, List<String>> result = splitQuery(url);
                                if (result.containsKey("code")) {
                                    System.out.println("bevat code");
                                    if (result.containsKey("error")) {
                                        System.out.println(String.format("{0}\r\n{1}", result.get("error"),
                                                result.get("errorDesc")));
                                    }
                                    System.out.println(result.get("code").get(0));
                                    String tokenError = GetToken(result.get("code").get(0), false);
                                    if (tokenError == null || "".equals(tokenError)) {
                                        System.out.println("Successful sign-in!");
                                        Log.e(TAG, "Successful sign-in!");
                                    } else {
                                        Log.e(TAG, "tokenError: " + tokenError);
                                    }
                                } else {
                                    System.out.println("Successful sign-out!");
                                }
                            }
                        } catch (IOException | URISyntaxException e) {
                            e.printStackTrace();
                        }

                        view.loadUrl(location);

                        return true;
                    }
                });
                LinearLayout linearLayout = new LinearLayout(thisActivity);
                linearLayout.setMinimumHeight(500);
                ArrayList<View> views = new ArrayList<View>();
                views.add(wv);
                linearLayout.addView(wv);
                EditText text = new EditText(thisActivity);
                text.setVisibility(View.GONE);
                linearLayout.addView(text);
                alert.setView(linearLayout);
                alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                    }
                });
                alert.show();
            } catch (Exception e) {
                Log.e(TAG, "dd");
            }
        }
    });
    Button showProfile = (Button) findViewById(R.id.button2);
    showProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showProfile();
        }
    });
    Button showSummmary = (Button) findViewById(R.id.button3);
    showSummmary.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showSummaries();
        }
    });

    if (savedInstanceState != null)

    {
        authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
    }

    buildFitnessClient();
}

From source file:jahirfiquitiva.iconshowcase.fragments.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button///from   w  ww  .  j  a v  a 2 s. c o m
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));
            } catch (ActivityNotFoundException e) {
                openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                        getString(R.string.donations__alert_dialog_no_browser));
            }

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                WebView.HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    try {
                        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (ActivityNotFoundException e) {
                        openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                                getString(R.string.donations__alert_dialog_no_browser));
                    }
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    TextView mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + mFlattrProjectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // disable scroll on touch
    mFlattrWebview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // already handled (returns true) when moving
            return (motionEvent.getAction() == MotionEvent.ACTION_MOVE);
        }
    });

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}

From source file:com.agustinprats.myhrv.fragment.MonitorFragment.java

/** Displays help to the user. */
private void showHelp() {

    AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
    alert.setTitle(getActivity().getString(R.string.Help));

    WebView wv = new WebView(getActivity());

    // loading the html file
    String htmlData = readAsset("help.html");

    // selecting the css based on the activity theme
    //        htmlData = htmlData.replaceFirst("CSS_FILE_NAME", ((MainActivity) getActivity()).isLightTheme() ? "light" : "dark");
    htmlData = htmlData.replaceFirst("CSS_FILE_NAME", "dark");
    // loading html in the webview
    wv.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);

    wv.setWebViewClient(new WebViewClient() {
        @Override//w  w w .  j av a2s.c o  m
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

    alert.setView(wv);
    alert.setNegativeButton(getActivity().getString(R.string.Close), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
    alert.show();
}

From source file:org.sufficientlysecure.donations.DonationsFragment.java

/**
 * Build view for Flattr. see Flattr API for more information:
 * http://developers.flattr.net/button///from w  ww  .  j  av a 2  s  .  co m
 */
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(11)
private void buildFlattrView() {
    final FrameLayout mLoadingFrame;
    final WebView mFlattrWebview;

    mFlattrWebview = (WebView) getActivity().findViewById(R.id.donations__flattr_webview);
    mLoadingFrame = (FrameLayout) getActivity().findViewById(R.id.donations__loading_frame);

    // disable hardware acceleration for this webview to get transparent background working
    if (Build.VERSION.SDK_INT >= 11) {
        mFlattrWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // define own webview client to override loading behaviour
    mFlattrWebview.setWebViewClient(new WebViewClient() {
        /**
         * Open all links in browser, not in webview
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlNewString)));
            } catch (ActivityNotFoundException e) {
                openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                        getString(R.string.donations__alert_dialog_no_browser));
            }

            return false;
        }

        /**
         * Links in the flattr iframe should load in the browser not in the iframe itself,
         * http:/
         * /stackoverflow.com/questions/5641626/how-to-get-webview-iframe-link-to-launch-the
         * -browser
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("flattr")) {
                HitTestResult result = view.getHitTestResult();
                if (result != null && result.getType() > 0) {
                    try {
                        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    } catch (ActivityNotFoundException e) {
                        openDialog(android.R.drawable.ic_dialog_alert, R.string.donations__alert_dialog_title,
                                getString(R.string.donations__alert_dialog_no_browser));
                    }
                    view.stopLoading();
                }
            }
        }

        /**
         * After loading is done, remove frame with progress circle
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            // remove loading frame, show webview
            if (mLoadingFrame.getVisibility() == View.VISIBLE) {
                mLoadingFrame.setVisibility(View.GONE);
                mFlattrWebview.setVisibility(View.VISIBLE);
            }
        }
    });

    // make text white and background transparent
    String htmlStart = "<html> <head><style type='text/css'>*{color: #FFFFFF; background-color: transparent;}</style>";

    // https is not working in android 2.1 and 2.2
    String flattrScheme;
    if (Build.VERSION.SDK_INT >= 9) {
        flattrScheme = "https://";
    } else {
        flattrScheme = "http://";
    }

    // set url of flattr link
    mFlattrUrlTextView = (TextView) getActivity().findViewById(R.id.donations__flattr_url);
    mFlattrUrlTextView.setText(flattrScheme + mFlattrUrl);

    String flattrJavascript = "<script type='text/javascript'>" + "/* <![CDATA[ */" + "(function() {"
            + "var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];"
            + "s.type = 'text/javascript';" + "s.async = true;" + "s.src = '" + flattrScheme
            + "api.flattr.com/js/0.6/load.js?mode=auto';" + "t.parentNode.insertBefore(s, t);" + "})();"
            + "/* ]]> */" + "</script>";
    String htmlMiddle = "</head> <body> <div align='center'>";
    String flattrHtml = "<a class='FlattrButton' style='display:none;' href='" + mFlattrProjectUrl
            + "' target='_blank'></a> <noscript><a href='" + flattrScheme + mFlattrUrl
            + "' target='_blank'> <img src='" + flattrScheme
            + "api.flattr.com/button/flattr-badge-large.png' alt='Flattr this' title='Flattr this' border='0' /></a></noscript>";
    String htmlEnd = "</div> </body> </html>";

    String flattrCode = htmlStart + flattrJavascript + htmlMiddle + flattrHtml + htmlEnd;

    mFlattrWebview.getSettings().setJavaScriptEnabled(true);

    mFlattrWebview.loadData(flattrCode, "text/html", "utf-8");

    // disable scroll on touch
    mFlattrWebview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // already handled (returns true) when moving
            return (motionEvent.getAction() == MotionEvent.ACTION_MOVE);
        }
    });

    // make background of webview transparent
    // has to be called AFTER loadData
    // http://stackoverflow.com/questions/5003156/android-webview-style-background-colortransparent-ignored-on-android-2-2
    mFlattrWebview.setBackgroundColor(0x00000000);
}

From source file:net.oremland.rss.reader.fragments.BrowserFragment.java

private void initializeViews(Bundle savedInstanceState) {
    if (savedInstanceState == null && getContext() != null) {
        boolean isTablet = getContext().getResources().getBoolean(R.bool.isTablet);
        WebSettings.ZoomDensity zoomDensity = isTablet ? WebSettings.ZoomDensity.MEDIUM
                : WebSettings.ZoomDensity.FAR;

        WebView description = (WebView) getView().findViewById(R.id.description);
        description.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        description.getSettings().setJavaScriptEnabled(true);
        description.getSettings().setPluginState(WebSettings.PluginState.ON);
        description.getSettings().setDefaultTextEncodingName("utf-8");
        description.getSettings().setLoadWithOverviewMode(true);
        description.getSettings().setDefaultZoom(zoomDensity);
        description.getSettings().setSupportZoom(true);
        description.getSettings().setBuiltInZoomControls(true);
        description.requestFocus(View.FOCUS_DOWN);
        description.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        description.getSettings().setUseWideViewPort(isTablet);
        description.setWebChromeClient(this.getWebChromeClient());
        description.setWebViewClient(this.getWebViewClient());
    }//from   www . java2s. c o  m
}

From source file:li.klass.fhem.fragments.AbstractWebViewFragment.java

@SuppressLint("SetJavaScriptEnabled")
@Override/* ww w.jav  a  2s  .  co  m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = super.onCreateView(inflater, container, savedInstanceState);
    if (view != null)
        return view;

    view = inflater.inflate(R.layout.webview, container, false);
    assert view != null;

    final WebView webView = (WebView) view.findViewById(R.id.webView);

    WebSettings settings = webView.getSettings();
    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);
    settings.setJavaScriptEnabled(true);
    settings.setBuiltInZoomControls(true);

    final ProgressDialog progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage(getResources().getString(R.string.loading));

    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress < 100) {
                progressDialog.setProgress(newProgress);
                progressDialog.show();
            } else {
                progressDialog.hide();
            }
        }
    });

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedSslError(WebView view, @NotNull SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @SuppressWarnings("ConstantConditions")
        @Override
        public void onReceivedHttpAuthRequest(WebView view, @NotNull HttpAuthHandler handler, String host,
                String realm) {
            FHEMServerSpec currentServer = connectionService.getCurrentServer(getActivity());
            String url = currentServer.getUrl();
            String alternativeUrl = trimToNull(currentServer.getAlternateUrl());
            try {

                String fhemUrlHost = new URL(url).getHost();
                String alternativeUrlHost = alternativeUrl == null ? null : new URL(alternativeUrl).getHost();
                String username = currentServer.getUsername();
                String password = currentServer.getPassword();

                if (host.startsWith(fhemUrlHost)
                        || (alternativeUrlHost != null && host.startsWith(alternativeUrlHost))) {
                    handler.proceed(username, password);
                } else {
                    handler.cancel();

                    Intent intent = new Intent(Actions.SHOW_TOAST);
                    intent.putExtra(BundleExtraKeys.STRING_ID, R.string.error_authentication);
                    getActivity().sendBroadcast(intent);
                }

            } catch (MalformedURLException e) {
                Intent intent = new Intent(Actions.SHOW_TOAST);
                intent.putExtra(BundleExtraKeys.STRING_ID, R.string.error_host_connection);
                getActivity().sendBroadcast(intent);
                LOG.error("malformed URL: " + url, e);

                handler.cancel();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if ("about:blank".equalsIgnoreCase(url)) {
                Optional<String> alternativeUrl = getAlternateLoadUrl();
                if (alternativeUrl.isPresent()) {
                    webView.loadUrl(alternativeUrl.get());
                }
            } else {
                onPageLoadFinishedCallback(view, url);
            }
        }
    });

    return view;
}

From source file:com.near.chimerarevo.fragments.PostFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void addWebObject(String width, String height, String url) {
    WebView wv = new WebView(getActivity());
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

    wv.setLayoutParams(params);/*from  w  w  w. j av a2s.c  o m*/
    wv.getSettings().setUseWideViewPort(true);
    wv.getSettings().setLoadWithOverviewMode(true);
    wv.getSettings().setSupportZoom(false);
    wv.setVerticalScrollBarEnabled(true);
    wv.setHorizontalScrollBarEnabled(true);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    wv.setWebViewClient(new WebViewClient());

    String frame = "<iframe width=\"" + width + "\" height=\"" + height + "\" frameborder=\"0\" src=\"" + url
            + "\"/>";
    wv.loadDataWithBaseURL(url, frame, "html/plain", "UTF-8", null);
    lay.addView(wv);
}