Example usage for android.webkit WebView setWebViewClient

List of usage examples for android.webkit WebView setWebViewClient

Introduction

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

Prototype

public void setWebViewClient(WebViewClient client) 

Source Link

Document

Sets the WebViewClient that will receive various notifications and requests.

Usage

From source file:jp.mixi.android.sdk.MixiContainerImpl.java

@Override
public void setupAd(Activity activity, AdParameter param) {
    WebView view = (WebView) activity.findViewById(R.id.webview);
    // view ??????????
    if (view == null) {
        Log.w(TAG, "webview not found.");
        return;/*from ww w  .  j  a  v  a  2  s .co  m*/
    }
    view.setWebViewClient(new MapWebViewClient(activity));
    if (param == null || param.headerPath == null) {
        Log.w(TAG, "path is null.");
        return;
    }
    view.loadUrl(param.headerPath);
    // ?????
    if (mSelector == Config.APPLICATION) {
        setupAppCounter();
    }
}

From source file:org.esupportail.nfctagdroid.NfcTacDroidActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ESUP_NFC_TAG_SERVER_URL = getEsupNfcTagServerUrl(getApplicationContext());
    //To keep session for desfire async requests
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    LocalStorage.getInstance(getApplicationContext());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getApplicationContext()));
    setContentView(R.layout.activity_main);
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    checkHardware(mAdapter);//from   w  ww . ja va 2 s.  c om
    localStorageDBHelper = LocalStorage.getInstance(this.getApplicationContext());
    String numeroId = localStorageDBHelper.getValue("numeroId");
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String imei = telephonyManager.getDeviceId();
    url = ESUP_NFC_TAG_SERVER_URL + "/nfc-index?numeroId=" + numeroId + "&imei=" + imei + "&macAddress="
            + getMacAddr() + "&apkVersion=" + getApkVersion();
    view = (WebView) this.findViewById(R.id.webView);
    view.clearCache(true);
    view.addJavascriptInterface(new LocalStorageJavaScriptInterface(this.getApplicationContext()),
            "AndroidLocalStorage");
    view.addJavascriptInterface(new AndroidJavaScriptInterface(this.getApplicationContext()), "Android");

    view.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (progress == 100) {
                AUTH_TYPE = localStorageDBHelper.getValue("authType");
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            log.info("Webview console message : " + consoleMessage.message());
            return false;
        }

    });

    view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            view.reload();
            return true;
        }
    });
    view.getSettings().setAllowContentAccess(true);
    WebSettings webSettings = view.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDatabasePath(this.getFilesDir().getParentFile().getPath() + "/databases/");

    view.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }

    });

    view.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
        }
    });

    view.loadUrl(url);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

From source file:com.baidu.cafe.local.record.WebElementRecorder.java

public void setHookedWebViewClient(final WebView webView, final String javaScript) {
    webView.post(new Runnable() {
        // @Override
        public void run() {
            final WebViewClient orginalWebViewClient = getOriginalWebViewClient(webView);
            if (orginalWebViewClient != null) {
                webView.setWebViewClient(new WebViewClient() {

                    HashMap<String, Boolean> invoke = new HashMap<String, Boolean>();

                    @Override/*www . ja v a 2  s.c om*/
                    public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
                        orginalWebViewClient.doUpdateVisitedHistory(view, url, isReload);
                    }

                    @Override
                    public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                        orginalWebViewClient.onFormResubmission(view, dontResend, resend);
                    }

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

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

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

                    @Override
                    public void onReceivedError(WebView view, int errorCode, String description,
                            String failingUrl) {
                        orginalWebViewClient.onReceivedError(view, errorCode, description, failingUrl);
                    }

                    @Override
                    public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
                            String realm) {
                        orginalWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm);
                    }

                    public void onReceivedLoginRequest(WebView view, String realm, String account,
                            String args) {
                        // do support onReceivedLoginRequest since the
                        // version 4.0
                        if (Build.VERSION.SDK_INT >= 14) {
                            orginalWebViewClient.onReceivedLoginRequest(view, realm, account, args);
                        }
                    }

                    @Override
                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                        orginalWebViewClient.onReceivedSslError(view, handler, error);
                    }

                    @Override
                    public void onScaleChanged(WebView view, float oldScale, float newScale) {
                        orginalWebViewClient.onScaleChanged(view, oldScale, newScale);
                    }

                    @Override
                    public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) {
                        orginalWebViewClient.onTooManyRedirects(view, cancelMsg, continueMsg);
                    }

                    @Override
                    public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
                        orginalWebViewClient.onUnhandledKeyEvent(view, event);
                    }

                    @Override
                    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                        if (Build.VERSION.SDK_INT >= 14) {
                            return orginalWebViewClient.shouldInterceptRequest(view, url);
                        } else {
                            return null;
                        }
                    }

                    @Override
                    public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                        return orginalWebViewClient.shouldOverrideKeyEvent(view, event);
                    }

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

                });
            } else {
                // set hook WebViewClient
                webView.setWebViewClient(new WebViewClient() {

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

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#onFormResubmission(android.webkit.WebView, android.os.Message, android.os.Message)
                     */
                    @Override
                    public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                        // TODO Auto-generated method stub
                        super.onFormResubmission(view, dontResend, resend);
                    }

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

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#onPageStarted(android.webkit.WebView, java.lang.String, android.graphics.Bitmap)
                     */
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        // TODO Auto-generated method stub
                        super.onPageStarted(view, url, favicon);
                    }

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#onReceivedError(android.webkit.WebView, int, java.lang.String, java.lang.String)
                     */
                    @Override
                    public void onReceivedError(WebView view, int errorCode, String description,
                            String failingUrl) {
                        // TODO Auto-generated method stub
                        super.onReceivedError(view, errorCode, description, failingUrl);
                    }

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#onReceivedHttpAuthRequest(android.webkit.WebView, android.webkit.HttpAuthHandler, java.lang.String, java.lang.String)
                     */
                    @Override
                    public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
                            String realm) {
                        // TODO Auto-generated method stub
                        super.onReceivedHttpAuthRequest(view, handler, host, realm);
                    }

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#onReceivedLoginRequest(android.webkit.WebView, java.lang.String, java.lang.String, java.lang.String)
                     */
                    @Override
                    public void onReceivedLoginRequest(WebView view, String realm, String account,
                            String args) {
                        // TODO Auto-generated method stub
                        super.onReceivedLoginRequest(view, realm, account, args);
                    }

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#onReceivedSslError(android.webkit.WebView, android.webkit.SslErrorHandler, android.net.http.SslError)
                     */
                    @Override
                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                        // TODO Auto-generated method stub
                        super.onReceivedSslError(view, handler, error);
                    }

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#onScaleChanged(android.webkit.WebView, float, float)
                     */
                    @Override
                    public void onScaleChanged(WebView view, float oldScale, float newScale) {
                        // TODO Auto-generated method stub
                        super.onScaleChanged(view, oldScale, newScale);
                    }

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#onTooManyRedirects(android.webkit.WebView, android.os.Message, android.os.Message)
                     */
                    @Override
                    public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) {
                        // TODO Auto-generated method stub
                        super.onTooManyRedirects(view, cancelMsg, continueMsg);
                    }

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#onUnhandledKeyEvent(android.webkit.WebView, android.view.KeyEvent)
                     */
                    @Override
                    public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
                        // TODO Auto-generated method stub
                        super.onUnhandledKeyEvent(view, event);
                    }

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, java.lang.String)
                     */
                    @Override
                    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                        // TODO Auto-generated method stub
                        return super.shouldInterceptRequest(view, url);
                    }

                    /* (non-Javadoc)
                     * @see android.webkit.WebViewClient#shouldOverrideKeyEvent(android.webkit.WebView, android.view.KeyEvent)
                     */
                    @Override
                    public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                        // TODO Auto-generated method stub
                        return super.shouldOverrideKeyEvent(view, event);
                    }

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

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(webView, url);
                        // print("webView onPageFinished: " + url);
                        if (url != null) {
                            hookWebElements(view, javaScript);
                        }
                    }
                });
            }
        }
    });
}

From source file:com.github.dfa.diaspora_android.activity.ShareActivity2.java

@SuppressLint("SetJavaScriptEnabled")
@Override//  w  ww . j  a  va2  s  .c  o  m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipeView.setEnabled(false);

    toolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (Helpers.isOnline(ShareActivity2.this)) {
                Intent intent = new Intent(ShareActivity2.this, MainActivity.class);
                startActivityForResult(intent, 100);
                overridePendingTransition(0, 0);
            } else {
                Snackbar.make(swipeView, R.string.no_internet, Snackbar.LENGTH_LONG).show();
            }
        }
    });

    podDomain = ((App) getApplication()).getSettings().getPodDomain();

    fab = (com.getbase.floatingactionbutton.FloatingActionsMenu) findViewById(R.id.fab_expand_menu_button);
    fab.setVisibility(View.GONE);

    webView = (WebView) findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    WebSettings wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, url);
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;

        }

        public void onPageFinished(WebView view, String url) {
            Log.i(TAG, "Finished loading URL: " + url);
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.hideTopBar(wv);
            }

            if (progress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.drawer_layout), "Unable to get image",
                            Snackbar.LENGTH_SHORT).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    Intent intent = getIntent();
    final Bundle extras = intent.getExtras();
    String action = intent.getAction();

    if (Intent.ACTION_SEND.equals(action)) {
        webView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {

                if (extras.containsKey(Intent.EXTRA_TEXT) && extras.containsKey(Intent.EXTRA_SUBJECT)) {
                    final String extraText = (String) extras.get(Intent.EXTRA_TEXT);
                    final String extraSubject = (String) extras.get(Intent.EXTRA_SUBJECT);

                    webView.setWebViewClient(new WebViewClient() {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {

                            finish();

                            Intent i = new Intent(ShareActivity2.this, MainActivity.class);
                            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(i);
                            overridePendingTransition(0, 0);

                            return false;
                        }
                    });

                    webView.loadUrl("javascript:(function() { "
                            + "document.getElementsByTagName('textarea')[0].style.height='110px'; "
                            + "document.getElementsByTagName('textarea')[0].innerHTML = '**[" + extraSubject
                            + "]** " + extraText + " *[shared with #DiasporaWebApp]*'; "
                            + "    if(document.getElementById(\"main_nav\")) {"
                            + "        document.getElementById(\"main_nav\").parentNode.removeChild("
                            + "        document.getElementById(\"main_nav\"));"
                            + "    } else if (document.getElementById(\"main-nav\")) {"
                            + "        document.getElementById(\"main-nav\").parentNode.removeChild("
                            + "        document.getElementById(\"main-nav\"));" + "    }" + "})();");

                }
            }
        });
    }

    if (savedInstanceState == null) {
        if (Helpers.isOnline(ShareActivity2.this)) {
            webView.loadUrl("https://" + podDomain + "/status_messages/new");
        } else {
            Snackbar.make(getWindow().findViewById(R.id.drawer_layout), R.string.no_internet,
                    Snackbar.LENGTH_SHORT).show();
        }
    }

}

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

@SuppressWarnings("deprecation")
@Override//  w w w. j a v  a2 s.  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.owncloud.android.ui.activity.ExternalSiteWebView.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log_OC.v(TAG, "onCreate() start");

    Bundle extras = getIntent().getExtras();
    String title = extras.getString(EXTRA_TITLE);
    String url = extras.getString(EXTRA_URL);
    menuItemId = extras.getInt(EXTRA_MENU_ITEM_ID);
    showSidebar = extras.getBoolean(EXTRA_SHOW_SIDEBAR);

    // show progress
    getWindow().requestFeature(Window.FEATURE_PROGRESS);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.externalsite_webview);

    WebView webview = (WebView) findViewById(R.id.webView);
    WebSettings webSettings = webview.getSettings();

    webview.setFocusable(true);//from  w w w . j a v a 2 s .  com
    webview.setFocusableInTouchMode(true);
    webview.setClickable(true);

    // setup toolbar
    setupToolbar();

    // setup drawer
    setupDrawer(menuItemId);

    if (!showSidebar) {
        setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    getSupportActionBar().setTitle(title);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // enable zoom
    webSettings.setSupportZoom(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setDisplayZoomControls(false);

    // Non-responsive webs are zoomed out when loaded
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);

    // user agent
    webSettings.setUserAgentString(MainApp.getUserAgent());

    // no private data storing
    webSettings.setSavePassword(false);
    webSettings.setSaveFormData(false);

    // disable local file access
    webSettings.setAllowFileAccess(false);

    // enable javascript
    webview.getSettings().setJavaScriptEnabled(true);

    final Activity activity = this;
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);

    webview.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            progressBar.setProgress(progress * 1000);
        }
    });

    webview.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(activity, getString(R.string.webview_error) + ": " + description, Toast.LENGTH_SHORT)
                    .show();
        }
    });

    webview.loadUrl(url);
}

From source file:com.github.dfa.diaspora_android.activity.ShareActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*ww w  .j  a va2 s . c  o  m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main__activity);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (toolbar != null) {
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Helpers.isOnline(ShareActivity.this)) {
                    Intent intent = new Intent(ShareActivity.this, MainActivity.class);
                    startActivityForResult(intent, 100);
                    overridePendingTransition(0, 0);
                    finish();
                } else {
                    Snackbar.make(swipeView, R.string.no_internet, Snackbar.LENGTH_LONG).show();
                }
            }
        });
    }
    setTitle(R.string.new_post);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipeView.setEnabled(false);

    podDomain = ((App) getApplication()).getSettings().getPodDomain();

    webView = (WebView) findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    WebSettings wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, url);
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;

        }

        public void onPageFinished(WebView view, String url) {
            Log.i(TAG, "Finished loading URL: " + url);
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.applyDiasporaMobileSiteChanges(wv);
            }

            if (progress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.main__layout), "Unable to get image",
                            Snackbar.LENGTH_LONG).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    if (savedInstanceState == null) {
        if (Helpers.isOnline(ShareActivity.this)) {
            webView.loadUrl("https://" + podDomain + "/status_messages/new");
        } else {
            Snackbar.make(getWindow().findViewById(R.id.main__layout), R.string.no_internet,
                    Snackbar.LENGTH_LONG).show();
        }
    }

    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {
                handleSendSubject(intent);
            } else {
                handleSendText(intent);
            }
        } else if (type.startsWith("image/")) {
            // TODO Handle single image being sent -> see manifest
            handleSendImage(intent);
        }
        //} else {
        // Handle other intents, such as being started from the home screen
    }

}

From source file:net.basov.ticketinfo.UI.java

public void displayWelcomeScreen(final WebView wv) {
    SharedPreferences defSharedPref = PreferenceManager.getDefaultSharedPreferences(wv.getContext());

    setWelcome("s_lang", defSharedPref.getString(wv.getContext().getString(R.string.pk_app_lang),
            wv.getContext().getString(R.string.pref_lang_def)));
    if (defSharedPref.getBoolean(wv.getContext().getString(R.string.pk_transliterate_flag), false)) {
        setWelcome("s_translit", "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">");

    } else {// w ww  .j av  a 2  s.  c o m
        setWelcome("s_translit", "<input type=\"checkbox\" disabled=\"disabled\">");
    }
    if (defSharedPref.getBoolean(wv.getContext().getString(R.string.pk_send_platform_info), true)) {
        setWelcome("s_sendinfo", "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">");
    } else {
        setWelcome("s_sendinfo", "<input type=\"checkbox\" disabled=\"disabled\">");
    }
    if (defSharedPref.getBoolean(wv.getContext().getString(R.string.pk_use_view_directory), false)) {
        setWelcome("s_use_view_directory",
                "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\">");
    } else {
        setWelcome("s_use_view_directory", "<input type=\"checkbox\" disabled=\"disabled\">");
    }

    wv.setWebViewClient(new MyWebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(wv, url);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                view.evaluateJavascript("javascript:jreplace('" + welcome_json.toString() + "')", null);
            } else {
                view.loadUrl("javascript:jreplace('" + welcome_json.toString() + "')", null);
            }
            wv.clearCache(true);
            wv.clearHistory();
        }
    });
    Context c = wv.getContext();
    wv.loadUrl("file:///android_asset/" + c.getString(R.string.welcome_ui_file));
}

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 a2  s.c  o  m*/
    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.mimo.service.api.MimoOauth2Client.java

/**
 * Instantiate a webview and allows the user to login to the Api form within
 * the application// w w w . j  av  a2s  . c  o m
 * 
 * @param p_view
 *            : Calling view
 * 
 * @param p_activity
 *            : Calling Activity reference
 **/

@SuppressLint("SetJavaScriptEnabled")
public void login(View p_view, Activity p_activity) {

    final Activity m_activity;
    m_activity = p_activity;
    String m_url = this.m_api.getAuthUrl();
    WebView m_webview = new WebView(p_view.getContext());
    m_webview.getSettings().setJavaScriptEnabled(true);
    m_webview.setVisibility(View.VISIBLE);
    m_activity.setContentView(m_webview);

    m_webview.requestFocus(View.FOCUS_DOWN);
    /**
     * Open the softkeyboard of the device to input the text in form which
     * loads in webview.
     */
    m_webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View p_v, MotionEvent p_event) {
            switch (p_event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!p_v.hasFocus()) {
                    p_v.requestFocus();
                }
                break;
            }
            return false;
        }
    });

    /**
     * Show the progressbar in the title of the activity untill the page
     * loads the give url.
     */
    m_webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView p_view, int p_newProgress) {
            ((Activity) m_context).setProgress(p_newProgress * 100);
            ((Activity) m_context).setTitle(MimoAPIConstants.DIALOG_TEXT_LOADING);

            if (p_newProgress == 100)
                ((Activity) m_context).setTitle(m_context.getString(R.string.app_name));
        }
    });

    m_webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView p_view, String p_url, Bitmap p_favicon) {
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView p_view, HttpAuthHandler p_handler, String p_url,
                String p_realm) {
            p_handler.proceed(MimoAPIConstants.USERNAME, MimoAPIConstants.PASSWORD);
        }

        public void onPageFinished(WebView p_view, String p_url) {
            if (MimoAPIConstants.DEBUG) {
                Log.d(TAG, "Page Url = " + p_url);
            }
            if (p_url.contains("?code=")) {
                if (p_url.indexOf("code=") != -1) {
                    String[] m_urlSplit = p_url.split("=");

                    String m_tempString1 = m_urlSplit[1];
                    if (MimoAPIConstants.DEBUG) {
                        Log.d(TAG, "TempString1 = " + m_tempString1);
                    }
                    String[] m_urlSplit1 = m_tempString1.split("&");

                    String m_code = m_urlSplit1[0];
                    if (MimoAPIConstants.DEBUG) {
                        Log.d(TAG, "code = " + m_code);
                    }
                    MimoOauth2Client.this.m_code = m_code;
                    Thread m_thread = new Thread() {
                        public void run() {
                            String m_token = requesttoken(MimoOauth2Client.this.m_code);

                            Log.d(TAG, "Token = " + m_token);

                            Intent m_navigateIntent = new Intent(m_activity, MimoTransactions.class);

                            m_navigateIntent.putExtra(MimoAPIConstants.KEY_TOKEN, m_token);

                            m_activity.startActivity(m_navigateIntent);
                        }
                    };
                    m_thread.start();
                } else {
                    if (MimoAPIConstants.DEBUG) {
                        Log.d(TAG, "going in else");
                    }
                }
            } else if (p_url.contains(MimoAPIConstants.URL_KEY_TOKEN)) {
                if (p_url.indexOf(MimoAPIConstants.URL_KEY_TOKEN) != -1) {
                    String[] m_urlSplit = p_url.split("=");
                    final String m_token = m_urlSplit[1];

                    Thread m_thread = new Thread() {
                        public void run() {
                            Intent m_navigateIntent = new Intent(m_activity, MimoTransactions.class);
                            m_navigateIntent.putExtra(MimoAPIConstants.KEY_TOKEN, m_token);
                            m_activity.startActivity(m_navigateIntent);
                        }
                    };
                    m_thread.start();
                }
            }
        };
    });

    m_webview.loadUrl(m_url);
}