Example usage for android.webkit WebView getSettings

List of usage examples for android.webkit WebView getSettings

Introduction

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

Prototype

public WebSettings getSettings() 

Source Link

Document

Gets the WebSettings object used to control the settings for this WebView.

Usage

From source file:im.vector.adapters.ImagesSliderAdapter.java

@Override
public Object instantiateItem(ViewGroup container, final int position) {
    View view = mLayoutInflater.inflate(R.layout.activity_image_web_view, null, false);

    // hide the pie chart
    final PieFractionView pieFractionView = (PieFractionView) view
            .findViewById(R.id.download_zoomed_image_piechart);
    pieFractionView.setVisibility(View.GONE);

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

    // black background
    view.setBackgroundColor(0xFF000000);
    webView.setBackgroundColor(0xFF000000);

    final SlidableImageInfo imageInfo = mListImageMessages.get(position);

    String mediaUrl = imageInfo.mImageUrl;
    final int rotationAngle = imageInfo.mRotationAngle;
    final String mimeType = imageInfo.mMimeType;

    final MXMediasCache mediasCache = Matrix.getInstance(this.context).getMediasCache();
    File mediaFile = mediasCache.mediaCacheFile(mediaUrl, mimeType);

    // is the high picture already downloaded ?
    if (null != mediaFile) {
        if (mHighResMediaIndex.indexOf(position) < 0) {
            mHighResMediaIndex.add(position);
        }/*from   ww  w  . j  ava  2  s  .  co m*/
    } else {
        // try to retrieve the thumbnail
        mediaFile = mediasCache.mediaCacheFile(mediaUrl, mMaxImageWidth, mMaxImageHeight, null);
    }

    // the thumbnail is not yet downloaded
    if (null == mediaFile) {
        // display nothing
        container.addView(view, 0);
        return view;
    }

    String mediaUri = "file://" + mediaFile.getPath();

    String css = computeCss(mediaUri, mMaxImageWidth, mMaxImageHeight, rotationAngle);
    final String viewportContent = "width=640";

    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setBuiltInZoomControls(true);

    loadImage(webView, Uri.parse(mediaUri), viewportContent, css);

    container.addView(view, 0);
    return view;
}

From source file:com.mario22gmail.license.nfc_project.NavigationDrawerActivity.java

public void OpenFacebook(String userName, String password) {
    WebView mWebview = (WebView) findViewById(R.id.webViewFb);
    String url = "https://www.facebook.com";
    js = "javascript:document.getElementsByName('email')[0].value = '" + userName
            + "';document.getElementsByName('pass')[0].value='" + password
            + "';document.getElementsByName('login')[0].click();";

    mWebview.loadUrl(url);//from  w  w w  .  ja v a2s. com
    WebSettings settings = mWebview.getSettings();
    settings.setJavaScriptEnabled(true);

    mWebview.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            if (Build.VERSION.SDK_INT >= 19) {
                view.evaluateJavascript(js, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {

                    }
                });
            } else {
                view.loadUrl(js);
            }
        }
    });
}

From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java

private void setWebView(final GalleryItemViewTag tag, final File file) {
    runOnUiThread(new Runnable() {
        private boolean oomFlag = false;

        private final ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        private void prepareWebView(WebView webView) {
            webView.setBackgroundColor(Color.TRANSPARENT);
            webView.setInitialScale(100);
            webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
                CompatibilityImpl.setScrollbarFadingEnabled(webView, true);
            }//from www .j av  a  2s  .  c o  m

            WebSettings settings = webView.getSettings();
            settings.setBuiltInZoomControls(true);
            settings.setSupportZoom(true);
            settings.setAllowFileAccess(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
                CompatibilityImpl.setDefaultZoomFAR(settings);
                CompatibilityImpl.setLoadWithOverviewMode(settings, true);
            }
            settings.setUseWideViewPort(true);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                CompatibilityImpl.setBlockNetworkLoads(settings, true);
            }

            setScaleWebView(webView);
        }

        private void setScaleWebView(final WebView webView) {
            Runnable callSetScaleWebView = new Runnable() {
                @Override
                public void run() {
                    setPrivateScaleWebView(webView);
                }
            };

            Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight());
            if (resolution.equals(0, 0)) {
                // wait until the view is measured and its size is known
                AppearanceUtils.callWhenLoaded(tag.layout, callSetScaleWebView);
            } else {
                callSetScaleWebView.run();
            }
        }

        private void setPrivateScaleWebView(WebView webView) {
            Point imageSize = getImageSize(file);
            Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight());

            //Logger.d(TAG, "Resolution: "+resolution.x+"x"+resolution.y);
            double scaleX = (double) resolution.x / (double) imageSize.x;
            double scaleY = (double) resolution.y / (double) imageSize.y;
            int scale = (int) Math.round(Math.min(scaleX, scaleY) * 100d);
            scale = Math.max(scale, 1);
            //Logger.d(TAG, "Scale: "+(Math.min(scaleX, scaleY) * 100d));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
                double picdpi = (getResources().getDisplayMetrics().density * 160d) / scaleX;
                if (picdpi >= 240) {
                    CompatibilityImpl.setDefaultZoomFAR(webView.getSettings());
                } else if (picdpi <= 120) {
                    CompatibilityImpl.setDefaultZoomCLOSE(webView.getSettings());
                } else {
                    CompatibilityImpl.setDefaultZoomMEDIUM(webView.getSettings());
                }
            }

            webView.setInitialScale(scale);
            webView.setPadding(0, 0, 0, 0);
        }

        private Point getImageSize(File file) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            return new Point(options.outWidth, options.outHeight);
        }

        private boolean useFallback(File file) {
            String path = file.getPath().toLowerCase(Locale.US);
            if (path.endsWith(".png"))
                return false;
            if (path.endsWith(".jpg"))
                return false;
            if (path.endsWith(".gif"))
                return false;
            if (path.endsWith(".jpeg"))
                return false;
            if (path.endsWith(".webp") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                return false;
            return true;
        }

        @Override
        public void run() {
            try {
                recycleTag(tag, false);
                WebView webView = new WebViewFixed(GalleryActivity.this);
                webView.setLayoutParams(MATCH_PARAMS);
                tag.layout.addView(webView);
                if (settings.fallbackWebView() || useFallback(file)) {
                    prepareWebView(webView);
                    webView.loadUrl(Uri.fromFile(file).toString());
                } else {
                    JSWebView.setImage(webView, file);
                }
                tag.thumbnailView.setVisibility(View.GONE);
                tag.loadingView.setVisibility(View.GONE);
                tag.layout.setVisibility(View.VISIBLE);
            } catch (OutOfMemoryError oom) {
                System.gc();
                Logger.e(TAG, oom);
                if (!oomFlag) {
                    oomFlag = true;
                    run();
                } else
                    showError(tag, getString(R.string.error_out_of_memory));
            }
        }

    });
}

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

@SuppressLint("NewApi")
private void updateWaypointInfo(double lat, double lon) {
    Androzic application = Androzic.getApplication();
    Activity activity = getActivity();/*  w  w w  .  j  a v  a  2 s. com*/
    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.baidu.cafe.local.record.WebElementRecorder.java

public void setHookedWebChromeClient(final WebView webView) {
    webElementEventCreator.prepareForStart();
    if (webView != null) {
        webView.post(new Runnable() {
            public void run() {
                webView.getSettings().setJavaScriptEnabled(true);
                final WebChromeClient originalWebChromeClient = getOriginalWebChromeClient(webView);
                if (originalWebChromeClient != null) {
                    webView.setWebChromeClient(new WebChromeClient() {
                        HashMap<String, Boolean> invoke = new HashMap<String, Boolean>();

                        /**
                         * Overrides onJsPrompt in order to create
                         * {@code WebElement} objects based on the web
                         * elements attributes prompted by the injections of
                         * JavaScript//from w ww. j  a  v a 2 s.  c om
                         */

                        @Override
                        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                                JsPromptResult r) {

                            if (message != null) {
                                if (message.endsWith("WebElementRecorder-finished")) {
                                    // Log.i("onJsPrompt : " + message);
                                    webElementEventCreator.setFinished(true);
                                } else {
                                    webElementEventCreator.createWebElementEvent(message, view);
                                }
                            }
                            r.confirm();
                            return true;
                        }

                        @Override
                        public Bitmap getDefaultVideoPoster() {
                            Bitmap ret = null;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.getDefaultVideoPoster();
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public View getVideoLoadingProgressView() {
                            View ret = null;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.getVideoLoadingProgressView();
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public void getVisitedHistory(ValueCallback<String[]> callback) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.getVisitedHistory(callback);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onCloseWindow(WebView window) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onCloseWindow(window);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onConsoleMessage(consoleMessage);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onConsoleMessage(message, lineNumber, sourceID);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
                                Message resultMsg) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onCreateWindow(view, isDialog, isUserGesture,
                                        resultMsg);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota,
                                long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota,
                                        estimatedDatabaseSize, totalQuota, quotaUpdater);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onGeolocationPermissionsHidePrompt() {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onGeolocationPermissionsHidePrompt();
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onHideCustomView() {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onHideCustomView();
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onJsAlert(view, url, message, result);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public boolean onJsBeforeUnload(WebView view, String url, String message,
                                JsResult result) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onJsBeforeUnload(view, url, message, result);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onJsConfirm(view, url, message, result);
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public boolean onJsTimeout() {
                            boolean ret = false;
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                ret = originalWebChromeClient.onJsTimeout();
                                invoke.put(funcName, false);
                            }
                            return ret;
                        }

                        @Override
                        public void onProgressChanged(WebView view, int newProgress) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onProgressChanged(view, newProgress);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onReachedMaxAppCacheSize(long requiredStorage, long quota,
                                QuotaUpdater quotaUpdater) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota,
                                        quotaUpdater);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onReceivedIcon(WebView view, Bitmap icon) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onReceivedIcon(view, icon);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onReceivedTitle(WebView view, String title) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onReceivedTitle(view, title);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed);
                                invoke.put(funcName, false);
                            }

                        }

                        @Override
                        public void onRequestFocus(WebView view) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onRequestFocus(view);
                                invoke.put(funcName, false);
                            }
                        }

                        @Override
                        public void onShowCustomView(View view, CustomViewCallback callback) {
                            String funcName = new Throwable().getStackTrace()[1].getMethodName();
                            if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                invoke.put(funcName, true);
                                originalWebChromeClient.onShowCustomView(view, callback);
                                invoke.put(funcName, false);
                            }
                        }

                        public void onShowCustomView(View view, int requestedOrientation,
                                CustomViewCallback callback) {
                            if (Build.VERSION.SDK_INT >= 14) {
                                String funcName = new Throwable().getStackTrace()[1].getMethodName();
                                if (invoke.get(funcName) == null || !invoke.get(funcName)) {
                                    invoke.put(funcName, true);
                                    originalWebChromeClient.onShowCustomView(view, requestedOrientation,
                                            callback);
                                    invoke.put(funcName, false);
                                }
                            }
                        }
                    });
                } else {
                    webView.setWebChromeClient(new WebChromeClient() {

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#getDefaultVideoPoster()
                         */
                        @Override
                        public Bitmap getDefaultVideoPoster() {
                            // TODO Auto-generated method stub
                            return super.getDefaultVideoPoster();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#getVideoLoadingProgressView()
                         */
                        @Override
                        public View getVideoLoadingProgressView() {
                            // TODO Auto-generated method stub
                            return super.getVideoLoadingProgressView();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#getVisitedHistory(android.webkit.ValueCallback)
                         */
                        @Override
                        public void getVisitedHistory(ValueCallback<String[]> callback) {
                            // TODO Auto-generated method stub
                            super.getVisitedHistory(callback);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onCloseWindow(android.webkit.WebView)
                         */
                        @Override
                        public void onCloseWindow(WebView window) {
                            // TODO Auto-generated method stub
                            super.onCloseWindow(window);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onConsoleMessage(android.webkit.ConsoleMessage)
                         */
                        @Override
                        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                            // TODO Auto-generated method stub
                            return super.onConsoleMessage(consoleMessage);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onConsoleMessage(java.lang.String, int, java.lang.String)
                         */
                        @Override
                        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                            // TODO Auto-generated method stub
                            super.onConsoleMessage(message, lineNumber, sourceID);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onCreateWindow(android.webkit.WebView, boolean, boolean, android.os.Message)
                         */
                        @Override
                        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
                                Message resultMsg) {
                            // TODO Auto-generated method stub
                            return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onExceededDatabaseQuota(java.lang.String, java.lang.String, long, long, long, android.webkit.WebStorage.QuotaUpdater)
                         */
                        @Override
                        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota,
                                long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) {
                            // TODO Auto-generated method stub
                            super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize,
                                    totalQuota, quotaUpdater);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onGeolocationPermissionsHidePrompt()
                         */
                        @Override
                        public void onGeolocationPermissionsHidePrompt() {
                            // TODO Auto-generated method stub
                            super.onGeolocationPermissionsHidePrompt();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onGeolocationPermissionsShowPrompt(java.lang.String, android.webkit.GeolocationPermissions.Callback)
                         */
                        @Override
                        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
                            // TODO Auto-generated method stub
                            super.onGeolocationPermissionsShowPrompt(origin, callback);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onHideCustomView()
                         */
                        @Override
                        public void onHideCustomView() {
                            // TODO Auto-generated method stub
                            super.onHideCustomView();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsAlert(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult)
                         */
                        @Override
                        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                            // TODO Auto-generated method stub
                            return super.onJsAlert(view, url, message, result);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsBeforeUnload(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult)
                         */
                        @Override
                        public boolean onJsBeforeUnload(WebView view, String url, String message,
                                JsResult result) {
                            // TODO Auto-generated method stub
                            return super.onJsBeforeUnload(view, url, message, result);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsConfirm(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult)
                         */
                        @Override
                        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                            // TODO Auto-generated method stub
                            return super.onJsConfirm(view, url, message, result);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsPrompt(android.webkit.WebView, java.lang.String, java.lang.String, java.lang.String, android.webkit.JsPromptResult)
                         */
                        @Override
                        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                                JsPromptResult result) {
                            if (message != null) {
                                if (message.endsWith("WebElementRecorder-finished")) {
                                    // Log.i("onJsPrompt : " + message);
                                    webElementEventCreator.setFinished(true);
                                } else {
                                    webElementEventCreator.createWebElementEvent(message, view);
                                }
                            }
                            result.confirm();
                            return true;
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onJsTimeout()
                         */
                        @Override
                        public boolean onJsTimeout() {
                            // TODO Auto-generated method stub
                            return super.onJsTimeout();
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onProgressChanged(android.webkit.WebView, int)
                         */
                        @Override
                        public void onProgressChanged(WebView view, int newProgress) {
                            // TODO Auto-generated method stub
                            super.onProgressChanged(view, newProgress);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onReachedMaxAppCacheSize(long, long, android.webkit.WebStorage.QuotaUpdater)
                         */
                        @Override
                        public void onReachedMaxAppCacheSize(long requiredStorage, long quota,
                                QuotaUpdater quotaUpdater) {
                            // TODO Auto-generated method stub
                            super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onReceivedIcon(android.webkit.WebView, android.graphics.Bitmap)
                         */
                        @Override
                        public void onReceivedIcon(WebView view, Bitmap icon) {
                            // TODO Auto-generated method stub
                            super.onReceivedIcon(view, icon);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onReceivedTitle(android.webkit.WebView, java.lang.String)
                         */
                        @Override
                        public void onReceivedTitle(WebView view, String title) {
                            // TODO Auto-generated method stub
                            super.onReceivedTitle(view, title);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onReceivedTouchIconUrl(android.webkit.WebView, java.lang.String, boolean)
                         */
                        @Override
                        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                            // TODO Auto-generated method stub
                            super.onReceivedTouchIconUrl(view, url, precomposed);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onRequestFocus(android.webkit.WebView)
                         */
                        @Override
                        public void onRequestFocus(WebView view) {
                            // TODO Auto-generated method stub
                            super.onRequestFocus(view);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onShowCustomView(android.view.View, android.webkit.WebChromeClient.CustomViewCallback)
                         */
                        @Override
                        public void onShowCustomView(View view, CustomViewCallback callback) {
                            // TODO Auto-generated method stub
                            super.onShowCustomView(view, callback);
                        }

                        /* (non-Javadoc)
                         * @see android.webkit.WebChromeClient#onShowCustomView(android.view.View, int, android.webkit.WebChromeClient.CustomViewCallback)
                         */
                        @Override
                        public void onShowCustomView(View view, int requestedOrientation,
                                CustomViewCallback callback) {
                            // TODO Auto-generated method stub
                            super.onShowCustomView(view, requestedOrientation, callback);
                        }

                    });
                }
            }
        });
    }
}

From source file:com.openatk.field_work.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.main_menu_add) {
        // Check if have an operation
        if (operationsList.isEmpty()) {
            // Show dialog to create operation
            createOperation(new Callable<Void>() {
                public Void call() {
                    //Do this after we create an operation
                    return addFieldMapView();
                }//from   w  w  w  .j  av  a 2  s.c  o m
            });
        } else {
            addFieldMapView();
        }
    } else if (item.getItemId() == R.id.main_menu_current_location) {
        Location myLoc = map.getMyLocation();
        if (myLoc == null) {
            Toast.makeText(this, "Still searching for your location", Toast.LENGTH_SHORT).show();
        } else {
            CameraPosition oldPos = map.getCameraPosition();
            CameraPosition newPos = new CameraPosition(new LatLng(myLoc.getLatitude(), myLoc.getLongitude()),
                    map.getMaxZoomLevel() - 5.0f, oldPos.tilt, oldPos.bearing);
            map.animateCamera(CameraUpdateFactory.newCameraPosition(newPos));
        }
    } else if (item.getItemId() == R.id.main_menu_layers) {
        MenuItem layers = menu.findItem(R.id.main_menu_layers);
        //TODO hazards
        /*if(showingHazards == false){
           showingHazards = true;
           layers.setTitle("Hide Hazards");
        } else {
           showingHazards = false;
           layers.setTitle("Show Hazards");
        }
        SharedPreferences prefs = getApplicationContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("showingHazards",showingHazards);
        editor.commit();
        drawHazards();*/
    } else if (item.getItemId() == R.id.main_menu_sync) {
        this.syncHelper.sync(this);
    } else if (item.getItemId() == R.id.main_menu_list_view) {
        // Show list view
        Log.d("MainActivity", "Showing list view");
        setState(STATE_LIST_VIEW);
    } else if (item.getItemId() == R.id.main_menu_map_view) {
        // Show map view
        Log.d("MainActivity", "Showing map view");
        setState(STATE_DEFAULT);
        closeKeyboard();
    } else if (item.getItemId() == R.id.main_menu_help) {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Help");
        WebView wv = new WebView(this);
        wv.loadUrl("file:///android_asset/Help.html");
        wv.getSettings().setSupportZoom(true);
        wv.getSettings().setBuiltInZoomControls(true);
        /*wv.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
           view.loadUrl(url);
           return true;
            }
        });*/
        alert.setView(wv);
        alert.setNegativeButton("Close", null);
        alert.show();
    } else if (item.getItemId() == R.id.main_menu_legal) {
        CharSequence licence = "The MIT License (MIT)\n" + "\n" + "Copyright (c) 2013 Purdue University\n"
                + "\n" + "Permission is hereby granted, free of charge, to any person obtaining a copy "
                + "of this software and associated documentation files (the \"Software\"), to deal "
                + "in the Software without restriction, including without limitation the rights "
                + "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell "
                + "copies of the Software, and to permit persons to whom the Software is "
                + "furnished to do so, subject to the following conditions:" + "\n"
                + "The above copyright notice and this permission notice shall be included in "
                + "all copies or substantial portions of the Software.\n" + "\n"
                + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR "
                + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, "
                + "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE "
                + "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER "
                + "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, "
                + "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN "
                + "THE SOFTWARE.\n";
        new AlertDialog.Builder(this).setTitle("Legal").setMessage(licence)
                .setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton("Close", null).show();
    } else if (item.getItemId() == R.id.main_menu_autosync) {
        TrelloSyncInfo syncInfo = syncHelper.getSyncInfo(getApplicationContext());

        int selected = -1;
        if (syncInfo != null) {
            if (syncInfo.getAutoSync() != null && syncInfo.getAutoSync() == false) {
                selected = 0;
            } else if (syncInfo.getInterval() != null) {
                Log.d("MainActivity", "syncInfo interval:" + syncInfo.getInterval());
                if (syncInfo.getInterval() == 60)
                    selected = 1;
                if (syncInfo.getInterval() == 60 * 5)
                    selected = 2;
                if (syncInfo.getInterval() == 60 * 10)
                    selected = 3;
                if (syncInfo.getInterval() == 60 * 30)
                    selected = 4;
            }
        }
        String[] options = { "Never", "1 min", "5 min", "10 min", "30 min" };
        new AlertDialog.Builder(this).setTitle("Autosync Interval")
                .setSingleChoiceItems(options, selected, new DialogInterface.OnClickListener() {
                    Integer devAutoSyncOnTrigger = 0;

                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            syncHelper.autoSyncOff(getApplicationContext());
                        } else if (which == 1) {
                            syncHelper.autoSyncOn(getApplicationContext(), 60);
                        } else if (which == 2) {
                            syncHelper.autoSyncOn(getApplicationContext(), 60 * 5);
                        } else if (which == 3) {
                            syncHelper.autoSyncOn(getApplicationContext(), 60 * 10);
                        } else if (which == 4) {
                            syncHelper.autoSyncOn(getApplicationContext(), 60 * 30);
                            devAutoSyncOnTrigger++;
                            if (devAutoSyncOnTrigger > 9) {
                                if (devAutoSyncOnTrigger % 2 == 0) {
                                    syncHelper.devAutoSyncOn(getApplicationContext(), 3);
                                    Toast.makeText(getApplicationContext(),
                                            "Presentation auto sync on, every 3 seconds.", Toast.LENGTH_SHORT)
                                            .show();
                                } else {
                                    syncHelper.devAutoSyncOff(getApplicationContext());
                                    Toast.makeText(getApplicationContext(), "Presentation auto sync off.",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }
                }).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                    }
                }).show();
    }
    return true;
}

From source file:nya.miku.wishmaster.ui.GalleryActivity.java

private void setWebView(final GalleryItemViewTag tag, final File file) {
    runOnUiThread(new Runnable() {
        private boolean oomFlag = false;

        private final ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        private void prepareWebView(WebView webView) {
            webView.setBackgroundColor(Color.TRANSPARENT);
            webView.setInitialScale(100);
            webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
                CompatibilityImpl.setScrollbarFadingEnabled(webView, true);
            }//  w  w w  . j  a v a 2  s  .com

            WebSettings settings = webView.getSettings();
            settings.setBuiltInZoomControls(true);
            settings.setSupportZoom(true);
            settings.setAllowFileAccess(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
                CompatibilityImpl.setDefaultZoomFAR(settings);
                CompatibilityImpl.setLoadWithOverviewMode(settings, true);
            }
            settings.setUseWideViewPort(true);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                CompatibilityImpl.setBlockNetworkLoads(settings, true);
            }

            setScaleWebView(webView);
        }

        private void setScaleWebView(final WebView webView) {
            Runnable callSetScaleWebView = new Runnable() {
                @Override
                public void run() {
                    setPrivateScaleWebView(webView);
                }
            };

            Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight());
            if (resolution.equals(0, 0)) {
                // wait until the view is measured and its size is known
                AppearanceUtils.callWhenLoaded(tag.layout, callSetScaleWebView);
            } else {
                callSetScaleWebView.run();
            }
        }

        private void setPrivateScaleWebView(WebView webView) {
            Point imageSize = getImageSize(file);
            Point resolution = new Point(tag.layout.getWidth(), tag.layout.getHeight());

            //Logger.d(TAG, "Resolution: "+resolution.x+"x"+resolution.y);
            double scaleX = (double) resolution.x / (double) imageSize.x;
            double scaleY = (double) resolution.y / (double) imageSize.y;
            int scale = (int) Math.round(Math.min(scaleX, scaleY) * 100d);
            scale = Math.max(scale, 1);
            //Logger.d(TAG, "Scale: "+(Math.min(scaleX, scaleY) * 100d));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
                double picdpi = (getResources().getDisplayMetrics().density * 160d) / scaleX;
                if (picdpi >= 240) {
                    CompatibilityImpl.setDefaultZoomFAR(webView.getSettings());
                } else if (picdpi <= 120) {
                    CompatibilityImpl.setDefaultZoomCLOSE(webView.getSettings());
                } else {
                    CompatibilityImpl.setDefaultZoomMEDIUM(webView.getSettings());
                }
            }

            webView.setInitialScale(scale);
            webView.setPadding(0, 0, 0, 0);
        }

        private Point getImageSize(File file) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            return new Point(options.outWidth, options.outHeight);
        }

        private boolean useFallback(File file) {
            String path = file.getPath().toLowerCase(Locale.US);
            if (path.endsWith(".png"))
                return false;
            if (path.endsWith(".jpg"))
                return false;
            if (path.endsWith(".gif"))
                return false;
            if (path.endsWith(".jpeg"))
                return false;
            if (path.endsWith(".webp") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                return false;
            return true;
        }

        @Override
        public void run() {
            try {
                recycleTag(tag, false);
                WebView webView = new WebViewFixed(GalleryActivity.this);
                webView.setLayoutParams(MATCH_PARAMS);
                tag.layout.addView(webView);
                if (settings.fallbackWebView() || useFallback(file)) {
                    prepareWebView(webView);
                    webView.loadUrl(Uri.fromFile(file).toString());
                } else {
                    JSWebView.setImage(webView, file);
                }
                tag.thumbnailView.setVisibility(View.GONE);
                tag.loadingView.setVisibility(View.GONE);
                tag.layout.setVisibility(View.VISIBLE);
            } catch (OutOfMemoryError oom) {
                MainApplication.freeMemory();
                Logger.e(TAG, oom);
                if (!oomFlag) {
                    oomFlag = true;
                    run();
                } else
                    showError(tag, getString(R.string.error_out_of_memory));
            }
        }

    });
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetAdapter.java

@SuppressWarnings("deprecation")
@Override//from   w  w  w.  ja v a  2s .  co m
public View getView(int position, View convertView, ViewGroup parent) {
    /* TODO: This definitely needs some huge refactoring */
    final RelativeLayout widgetView;
    TextView labelTextView;
    TextView valueTextView;
    int widgetLayout;
    String[] splitString;
    OpenHABWidget openHABWidget = getItem(position);
    int screenWidth = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay().getWidth();
    switch (this.getItemViewType(position)) {
    case TYPE_FRAME:
        widgetLayout = R.layout.openhabwidgetlist_frameitem;
        break;
    case TYPE_GROUP:
        widgetLayout = R.layout.openhabwidgetlist_groupitem;
        break;
    case TYPE_SECTIONSWITCH:
        widgetLayout = R.layout.openhabwidgetlist_sectionswitchitem;
        break;
    case TYPE_SWITCH:
        widgetLayout = R.layout.openhabwidgetlist_switchitem;
        break;
    case TYPE_ROLLERSHUTTER:
        widgetLayout = R.layout.openhabwidgetlist_rollershutteritem;
        break;
    case TYPE_TEXT:
        widgetLayout = R.layout.openhabwidgetlist_textitem;
        break;
    case TYPE_SLIDER:
        widgetLayout = R.layout.openhabwidgetlist_slideritem;
        break;
    case TYPE_IMAGE:
        widgetLayout = R.layout.openhabwidgetlist_imageitem;
        break;
    case TYPE_SELECTION:
        widgetLayout = R.layout.openhabwidgetlist_selectionitem;
        break;
    case TYPE_SETPOINT:
        widgetLayout = R.layout.openhabwidgetlist_setpointitem;
        break;
    case TYPE_CHART:
        widgetLayout = R.layout.openhabwidgetlist_chartitem;
        break;
    case TYPE_VIDEO:
        widgetLayout = R.layout.openhabwidgetlist_videoitem;
        break;
    case TYPE_VIDEO_MJPEG:
        widgetLayout = R.layout.openhabwidgetlist_videomjpegitem;
        break;
    case TYPE_WEB:
        widgetLayout = R.layout.openhabwidgetlist_webitem;
        break;
    case TYPE_COLOR:
        widgetLayout = R.layout.openhabwidgetlist_coloritem;
        break;
    default:
        widgetLayout = R.layout.openhabwidgetlist_genericitem;
        break;
    }
    if (convertView == null) {
        widgetView = new RelativeLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater vi;
        vi = (LayoutInflater) getContext().getSystemService(inflater);
        vi.inflate(widgetLayout, widgetView, true);
    } else {
        widgetView = (RelativeLayout) convertView;
    }

    // Process the colour attributes
    Integer iconColor = openHABWidget.getIconColor();
    Integer labelColor = openHABWidget.getLabelColor();
    Integer valueColor = openHABWidget.getValueColor();

    // Process widgets icon image
    MySmartImageView widgetImage = (MySmartImageView) widgetView.findViewById(R.id.widgetimage);
    // Some of widgets, for example Frame doesnt' have an icon, so...
    if (widgetImage != null) {
        if (openHABWidget.getIcon() != null) {
            // This is needed to escape possible spaces and everything according to rfc2396
            String iconUrl = openHABBaseUrl + "images/" + Uri.encode(openHABWidget.getIcon() + ".png");
            //                Log.d(TAG, "Will try to load icon from " + iconUrl);
            // Now set image URL
            widgetImage.setImageUrl(iconUrl, R.drawable.blank_icon, openHABUsername, openHABPassword);
            if (iconColor != null)
                widgetImage.setColorFilter(iconColor);
            else
                widgetImage.clearColorFilter();
        }
    }
    TextView defaultTextView = new TextView(widgetView.getContext());
    // Get TextView for widget label and set it's color
    labelTextView = (TextView) widgetView.findViewById(R.id.widgetlabel);
    // Change label color only for non-frame widgets
    if (labelColor != null && labelTextView != null && this.getItemViewType(position) != TYPE_FRAME) {
        Log.d(TAG, String.format("Setting label color to %d", labelColor));
        labelTextView.setTextColor(labelColor);
    } else if (labelTextView != null && this.getItemViewType(position) != TYPE_FRAME)
        labelTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    // Get TextView for widget value and set it's color
    valueTextView = (TextView) widgetView.findViewById(R.id.widgetvalue);
    if (valueColor != null && valueTextView != null) {
        Log.d(TAG, String.format("Setting value color to %d", valueColor));
        valueTextView.setTextColor(valueColor);
    } else if (valueTextView != null)
        valueTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    defaultTextView = null;
    switch (getItemViewType(position)) {
    case TYPE_FRAME:
        if (labelTextView != null) {
            labelTextView.setText(openHABWidget.getLabel());
            if (valueColor != null)
                labelTextView.setTextColor(valueColor);
        }
        widgetView.setClickable(false);
        if (openHABWidget.getLabel().length() > 0) { // hide empty frames
            widgetView.setVisibility(View.VISIBLE);
            labelTextView.setVisibility(View.VISIBLE);
        } else {
            widgetView.setVisibility(View.GONE);
            labelTextView.setVisibility(View.GONE);
        }
        break;
    case TYPE_GROUP:
        if (labelTextView != null && valueTextView != null) {
            splitString = openHABWidget.getLabel().split("\\[|\\]");
            labelTextView.setText(splitString[0]);
            if (splitString.length > 1) { // We have some value
                valueTextView.setText(splitString[1]);
            } else {
                // This is needed to clean up cached TextViews
                valueTextView.setText("");
            }
        }
        break;
    case TYPE_SECTIONSWITCH:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (splitString.length > 1 && valueTextView != null) { // We have some value
            valueTextView.setText(splitString[1]);
        } else {
            // This is needed to clean up cached TextViews
            valueTextView.setText("");
        }
        RadioGroup sectionSwitchRadioGroup = (RadioGroup) widgetView.findViewById(R.id.sectionswitchradiogroup);
        // As we create buttons in this radio in runtime, we need to remove all
        // exiting buttons first
        sectionSwitchRadioGroup.removeAllViews();
        sectionSwitchRadioGroup.setTag(openHABWidget);
        Iterator<OpenHABWidgetMapping> sectionMappingIterator = openHABWidget.getMappings().iterator();
        while (sectionMappingIterator.hasNext()) {
            OpenHABWidgetMapping widgetMapping = sectionMappingIterator.next();
            SegmentedControlButton segmentedControlButton = (SegmentedControlButton) LayoutInflater
                    .from(sectionSwitchRadioGroup.getContext())
                    .inflate(R.layout.openhabwidgetlist_sectionswitchitem_button, sectionSwitchRadioGroup,
                            false);
            segmentedControlButton.setText(widgetMapping.getLabel());
            segmentedControlButton.setTag(widgetMapping.getCommand());
            if (openHABWidget.getItem() != null && widgetMapping.getCommand() != null) {
                if (widgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    segmentedControlButton.setChecked(true);
                } else {
                    segmentedControlButton.setChecked(false);
                }
            } else {
                segmentedControlButton.setChecked(false);
            }
            segmentedControlButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i(TAG, "Button clicked");
                    RadioGroup group = (RadioGroup) view.getParent();
                    if (group.getTag() != null) {
                        OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                        SegmentedControlButton selectedButton = (SegmentedControlButton) view;
                        if (selectedButton.getTag() != null) {
                            sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                        }
                    }
                }
            });
            sectionSwitchRadioGroup.addView(segmentedControlButton);
        }

        sectionSwitchRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                SegmentedControlButton selectedButton = (SegmentedControlButton) group.findViewById(checkedId);
                if (selectedButton != null) {
                    Log.d(TAG, "Selected " + selectedButton.getText());
                    Log.d(TAG, "Command = " + (String) selectedButton.getTag());
                    //                  radioWidget.getItem().sendCommand((String)selectedButton.getTag());
                    sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                }
            }
        });
        break;
    case TYPE_SWITCH:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        SwitchCompat switchSwitch = (SwitchCompat) widgetView.findViewById(R.id.switchswitch);
        if (openHABWidget.hasItem()) {
            if (openHABWidget.getItem().getStateAsBoolean()) {
                switchSwitch.setChecked(true);
            } else {
                switchSwitch.setChecked(false);
            }
        }
        switchSwitch.setTag(openHABWidget.getItem());
        switchSwitch.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                SwitchCompat switchSwitch = (SwitchCompat) v;
                OpenHABItem linkedItem = (OpenHABItem) switchSwitch.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    if (!switchSwitch.isChecked()) {
                        sendItemCommand(linkedItem, "ON");
                    } else {
                        sendItemCommand(linkedItem, "OFF");
                    }
                return false;
            }
        });
        break;
    case TYPE_COLOR:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton colorUpButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_up);
        ImageButton colorDownButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_down);
        ImageButton colorColorButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_color);
        colorUpButton.setTag(openHABWidget.getItem());
        colorDownButton.setTag(openHABWidget.getItem());
        colorColorButton.setTag(openHABWidget.getItem());
        colorUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "ON");
                return false;
            }
        });
        colorDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "OFF");
                return false;
            }
        });
        colorColorButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (colorItem != null) {
                    if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
                        Log.d(TAG, "Time to launch color picker!");
                        ColorPickerDialog colorDialog = new ColorPickerDialog(widgetView.getContext(),
                                new OnColorChangedListener() {
                                    public void colorChanged(float[] hsv, View v) {
                                        Log.d(TAG, "New color HSV = " + hsv[0] + ", " + hsv[1] + ", " + hsv[2]);
                                        String newColor = String.valueOf(hsv[0]) + ","
                                                + String.valueOf(hsv[1] * 100) + ","
                                                + String.valueOf(hsv[2] * 100);
                                        OpenHABItem colorItem = (OpenHABItem) v.getTag();
                                        sendItemCommand(colorItem, newColor);
                                    }
                                }, colorItem.getStateAsHSV());
                        colorDialog.setTag(colorItem);
                        colorDialog.show();
                    }
                }
                return false;
            }
        });
        break;
    case TYPE_ROLLERSHUTTER:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton rollershutterUpButton = (ImageButton) widgetView.findViewById(R.id.rollershutterbutton_up);
        ImageButton rollershutterStopButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_stop);
        ImageButton rollershutterDownButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_down);
        rollershutterUpButton.setTag(openHABWidget.getItem());
        rollershutterStopButton.setTag(openHABWidget.getItem());
        rollershutterDownButton.setTag(openHABWidget.getItem());
        rollershutterUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "UP");
                return false;
            }
        });
        rollershutterStopButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "STOP");
                return false;
            }
        });
        rollershutterDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "DOWN");
                return false;
            }
        });
        break;
    case TYPE_TEXT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            if (splitString.length > 0) {
                labelTextView.setText(splitString[0]);
            } else {
                labelTextView.setText(openHABWidget.getLabel());
            }
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            } else {
                // If value is empty, hide TextView to fix vertical alignment of label
                valueTextView.setVisibility(View.GONE);
                valueTextView.setText("");
            }
        break;
    case TYPE_SLIDER:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        SeekBar sliderSeekBar = (SeekBar) widgetView.findViewById(R.id.sliderseekbar);
        if (openHABWidget.hasItem()) {
            sliderSeekBar.setTag(openHABWidget.getItem());
            sliderSeekBar.setProgress(openHABWidget.getItem().getStateAsFloat().intValue());
            sliderSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                }

                public void onStartTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStartTrackingTouch position = " + seekBar.getProgress());
                }

                public void onStopTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStopTrackingTouch position = " + seekBar.getProgress());
                    OpenHABItem sliderItem = (OpenHABItem) seekBar.getTag();
                    //                     sliderItem.sendCommand(String.valueOf(seekBar.getProgress()));
                    if (sliderItem != null && seekBar != null)
                        sendItemCommand(sliderItem, String.valueOf(seekBar.getProgress()));
                }
            });
            if (volumeUpWidget == null) {
                volumeUpWidget = sliderSeekBar;
                volumeDownWidget = sliderSeekBar;
            }
        }
        break;
    case TYPE_IMAGE:
        MySmartImageView imageImage = (MySmartImageView) widgetView.findViewById(R.id.imageimage);
        imageImage.setImageUrl(ensureAbsoluteURL(openHABBaseUrl, openHABWidget.getUrl()), false,
                openHABUsername, openHABPassword);
        //          ViewGroup.LayoutParams imageLayoutParams = imageImage.getLayoutParams();
        //          float imageRatio = imageImage.getDrawable().getIntrinsicWidth()/imageImage.getDrawable().getIntrinsicHeight();
        //          imageLayoutParams.height = (int) (screenWidth/imageRatio);
        //          imageImage.setLayoutParams(imageLayoutParams);
        if (openHABWidget.getRefresh() > 0) {
            imageImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(imageImage);
        }
        break;
    case TYPE_CHART:
        MySmartImageView chartImage = (MySmartImageView) widgetView.findViewById(R.id.chartimage);
        //Always clear the drawable so no images from recycled views appear
        chartImage.setImageDrawable(null);
        OpenHABItem chartItem = openHABWidget.getItem();
        Random random = new Random();
        String chartUrl = "";
        if (chartItem != null) {
            if (chartItem.getType().equals("GroupItem")) {
                chartUrl = openHABBaseUrl + "chart?groups=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            } else {
                chartUrl = openHABBaseUrl + "chart?items=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            }
            if (openHABWidget.getService() != null && openHABWidget.getService().length() > 0) {
                chartUrl += "&service=" + openHABWidget.getService();
            }
        }
        Log.d(TAG, "Chart url = " + chartUrl);
        if (chartImage == null)
            Log.e(TAG, "chartImage == null !!!");
        ViewGroup.LayoutParams chartLayoutParams = chartImage.getLayoutParams();
        chartLayoutParams.height = (int) (screenWidth / 2);
        chartImage.setLayoutParams(chartLayoutParams);
        chartUrl += "&w=" + String.valueOf(screenWidth);
        chartUrl += "&h=" + String.valueOf(screenWidth / 2);
        chartImage.setImageUrl(chartUrl, false, openHABUsername, openHABPassword);
        // TODO: This is quite dirty fix to make charts look full screen width on all displays
        if (openHABWidget.getRefresh() > 0) {
            chartImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(chartImage);
        }
        Log.d(TAG, "chart size = " + chartLayoutParams.width + " " + chartLayoutParams.height);
        break;
    case TYPE_VIDEO:
        VideoView videoVideo = (VideoView) widgetView.findViewById(R.id.videovideo);
        Log.d(TAG, "Opening video at " + openHABWidget.getUrl());
        // TODO: This is quite dirty fix to make video look maximum available size on all screens
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        ViewGroup.LayoutParams videoLayoutParams = videoVideo.getLayoutParams();
        videoLayoutParams.height = (int) (wm.getDefaultDisplay().getWidth() / 1.77);
        videoVideo.setLayoutParams(videoLayoutParams);
        // We don't have any event handler to know if the VideoView is on the screen
        // so we manage an array of all videos to stop them when user leaves the page
        if (!videoWidgetList.contains(videoVideo))
            videoWidgetList.add(videoVideo);
        // Start video
        if (!videoVideo.isPlaying()) {
            videoVideo.setVideoURI(Uri.parse(openHABWidget.getUrl()));
            videoVideo.start();
        }
        Log.d(TAG, "Video height is " + videoVideo.getHeight());
        break;
    case TYPE_VIDEO_MJPEG:
        Log.d(TAG, "Video is mjpeg");
        ImageView mjpegImage = (ImageView) widgetView.findViewById(R.id.mjpegimage);
        MjpegStreamer mjpegStreamer = new MjpegStreamer(openHABWidget.getUrl(), this.openHABUsername,
                this.openHABPassword, this.getContext());
        mjpegStreamer.setTargetImageView(mjpegImage);
        mjpegStreamer.start();
        if (!mjpegWidgetList.contains(mjpegStreamer))
            mjpegWidgetList.add(mjpegStreamer);
        break;
    case TYPE_WEB:
        WebView webWeb = (WebView) widgetView.findViewById(R.id.webweb);
        if (openHABWidget.getHeight() > 0) {
            ViewGroup.LayoutParams webLayoutParams = webWeb.getLayoutParams();
            webLayoutParams.height = openHABWidget.getHeight() * 80;
            webWeb.setLayoutParams(webLayoutParams);
        }
        webWeb.setWebViewClient(
                new AnchorWebViewClient(openHABWidget.getUrl(), this.openHABUsername, this.openHABPassword));
        webWeb.getSettings().setJavaScriptEnabled(true);
        webWeb.loadUrl(openHABWidget.getUrl());
        break;
    case TYPE_SELECTION:
        int spinnerSelectedIndex = -1;
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        final Spinner selectionSpinner = (Spinner) widgetView.findViewById(R.id.selectionspinner);
        selectionSpinner.setOnItemSelectedListener(null);
        ArrayList<String> spinnerArray = new ArrayList<String>();
        Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings().iterator();
        while (mappingIterator.hasNext()) {
            OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
            spinnerArray.add(openHABWidgetMapping.getLabel());
            if (openHABWidgetMapping.getCommand() != null && openHABWidget.getItem() != null)
                if (openHABWidgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    spinnerSelectedIndex = spinnerArray.size() - 1;
                }
        }
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this.getContext(),
                android.R.layout.simple_spinner_item, spinnerArray);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        selectionSpinner.setAdapter(spinnerAdapter);
        selectionSpinner.setTag(openHABWidget);
        if (spinnerSelectedIndex >= 0) {
            Log.d(TAG, "Setting spinner selected index to " + String.valueOf(spinnerSelectedIndex));
            selectionSpinner.setSelection(spinnerSelectedIndex);
        } else {
            Log.d(TAG, "Not setting spinner selected index");
        }
        selectionSpinner.post(new Runnable() {
            @Override
            public void run() {
                selectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View view, int index, long id) {
                        Log.d(TAG, "Spinner item click on index " + index);
                        Spinner spinner = (Spinner) parent;
                        String selectedLabel = (String) spinner.getAdapter().getItem(index);
                        Log.d(TAG, "Spinner onItemSelected selected label = " + selectedLabel);
                        OpenHABWidget openHABWidget = (OpenHABWidget) parent.getTag();
                        if (openHABWidget != null) {
                            Log.d(TAG, "Label selected = " + openHABWidget.getMapping(index).getLabel());
                            Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings()
                                    .iterator();
                            while (mappingIterator.hasNext()) {
                                OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
                                if (openHABWidgetMapping.getLabel().equals(selectedLabel)) {
                                    Log.d(TAG, "Spinner onItemSelected found match with "
                                            + openHABWidgetMapping.getCommand());
                                    if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() != null) {
                                        // Only send the command for selection of selected command will change the state
                                        if (!openHABWidget.getItem().getState()
                                                .equals(openHABWidgetMapping.getCommand())) {
                                            Log.d(TAG,
                                                    "Spinner onItemSelected selected label command != current item state");
                                            sendItemCommand(openHABWidget.getItem(),
                                                    openHABWidgetMapping.getCommand());
                                        }
                                    } else if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() == null) {
                                        Log.d(TAG,
                                                "Spinner onItemSelected selected label command and state == null");
                                        sendItemCommand(openHABWidget.getItem(),
                                                openHABWidgetMapping.getCommand());
                                    }
                                }
                            }
                        }
                        //               if (!openHABWidget.getItem().getState().equals(openHABWidget.getMapping(index).getCommand()))
                        //                  sendItemCommand(openHABWidget.getItem(),
                        //                        openHABWidget.getMapping(index).getCommand());
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
            }
        });
        break;
    case TYPE_SETPOINT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            }
        Button setPointMinusButton = (Button) widgetView.findViewById(R.id.setpointbutton_minus);
        Button setPointPlusButton = (Button) widgetView.findViewById(R.id.setpointbutton_plus);
        setPointMinusButton.setTag(openHABWidget);
        setPointPlusButton.setTag(openHABWidget);
        setPointMinusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Minus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue - setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));

            }
        });
        setPointPlusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Plus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue + setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));
            }
        });
        if (volumeUpWidget == null) {
            volumeUpWidget = setPointPlusButton;
            volumeDownWidget = setPointMinusButton;
        }
        break;
    default:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        break;
    }
    LinearLayout dividerLayout = (LinearLayout) widgetView.findViewById(R.id.listdivider);
    if (dividerLayout != null) {
        if (position < this.getCount() - 1) {
            if (this.getItemViewType(position + 1) == TYPE_FRAME) {
                dividerLayout.setVisibility(View.GONE); // hide dividers before frame widgets
            } else {
                dividerLayout.setVisibility(View.VISIBLE); // show dividers for all others
            }
        } else { // last widget in the list, hide divider
            dividerLayout.setVisibility(View.GONE);
        }
    }
    return widgetView;
}

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  www.  j ava2s  . co 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:io.selendroid.server.model.SelendroidWebDriver.java

private void configureWebView(final WebView view) {
    ServerInstrumentation.getInstance().getCurrentActivity().runOnUiThread(new Runnable() {

        @Override//from w w w  .j  a  v  a  2  s .co  m
        public void run() {
            try {
                view.clearCache(true);
                view.clearFormData();
                view.clearHistory();
                view.setFocusable(true);
                view.setFocusableInTouchMode(true);
                view.setNetworkAvailable(true);
                // need to check the class name rather than checking instanceof
                // since when it is not an instanceof, it likely means the app under test
                // does not contain the Cordova project and this will cause a RuntimeException
                if (view.getClass().getSimpleName().equalsIgnoreCase("CordovaWebView")) {
                    CordovaWebView webview = (CordovaWebView) view;
                    CordovaInterface ci = null;
                    chromeClient = new ExtendedCordovaChromeClient(null, webview);
                } else {
                    chromeClient = new SelendroidWebChromeClient();
                }
                view.setWebChromeClient(chromeClient);

                WebSettings settings = view.getSettings();
                settings.setJavaScriptCanOpenWindowsAutomatically(true);
                settings.setSupportMultipleWindows(true);
                settings.setBuiltInZoomControls(true);
                settings.setJavaScriptEnabled(true);
                settings.setAppCacheEnabled(true);
                settings.setAppCacheMaxSize(10 * 1024 * 1024);
                settings.setAppCachePath("");
                settings.setDatabaseEnabled(true);
                settings.setDomStorageEnabled(true);
                settings.setGeolocationEnabled(true);
                settings.setSaveFormData(false);
                settings.setSavePassword(false);
                settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
                // Flash settings
                settings.setPluginState(WebSettings.PluginState.ON);

                // Geo location settings
                settings.setGeolocationEnabled(true);
                settings.setGeolocationDatabasePath("/data/data/selendroid");
            } catch (Exception e) {
                SelendroidLogger.error("Error configuring web view", e);
            }
        }
    });
}