Example usage for android.webkit WebView requestFocus

List of usage examples for android.webkit WebView requestFocus

Introduction

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

Prototype

public final boolean requestFocus(int direction) 

Source Link

Document

Call this to try to give focus to a specific view or to one of its descendants and give it a hint about what direction focus is heading.

Usage

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/*ww w. j a  v a2 s  .  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);
}

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

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

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

From source file:com.microsoft.windowsazure.mobileservices.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 * // w ww  .  ja v  a 2s  .  c o m
 * @param provider
 *            The provider used for the authentication process
 * @param startUrl
 *            The initial URL for the authentication process
 * @param endUrl
 *            The final URL for the authentication process
 * @param context
 *            The context used to create the authentication dialog
 * @param callback
 *            Callback to invoke when the authentication process finishes
 */
private void showLoginUI(final String startUrl, final String endUrl, final Context context,
        LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });
    wv.getSettings().setJavaScriptEnabled(true);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int webViewHeight = displaymetrics.heightPixels;

    wv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, webViewHeight));

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished
            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:com.azure.webapi.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 * //  ww w. j  ava  2  s  .c  om
 * @param provider
 *            The provider used for the authentication process
 * @param startUrl
 *            The initial URL for the authentication process
 * @param endUrl
 *            The final URL for the authentication process
 * @param context
 *            The context used to create the authentication dialog
 * @param callback
 *            Callback to invoke when the authentication process finishes
 */
protected void showLoginUI(MobileServiceAuthenticationProvider provider, final String startUrl,
        final String endUrl, final Context context, LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setTitle("Connecting to a service");
    builder.setCancelable(true);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });

    // Set cancel button's action
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
            wv.destroy();
        }
    });

    wv.getSettings().setJavaScriptEnabled(true);

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished
            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:com.microsoft.windowsazure.mobileservices.authentication.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 *
 * @param startUrl The initial URL for the authentication process
 * @param endUrl   The final URL for the authentication process
 * @param context  The context used to create the authentication dialog
 * @param callback Callback to invoke when the authentication process finishes
 *//*from ww w . ja  v a2  s  .  com*/
private void showLoginUIInternal(final String startUrl, final String endUrl, final Context context,
        LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });

    wv.getSettings().setJavaScriptEnabled(true);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int webViewHeight = displaymetrics.heightPixels - 100;

    wv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, webViewHeight));

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished

            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:org.liberty.android.fantastischmemo.downloader.google.GoogleOAuth2AccessCodeRetrievalFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final View v = inflater.inflate(R.layout.oauth_login_layout, container, false);
    final WebView webview = (WebView) v.findViewById(R.id.login_page);
    final View loadingText = v.findViewById(R.id.auth_page_load_text);
    final View progressDialog = v.findViewById(R.id.auth_page_load_progress);
    final LinearLayout ll = (LinearLayout) v.findViewById(R.id.ll);

    // We have to set up the dialog's webview size manually or the webview will be zero size.
    // This should be a bug of Android.
    Rect displayRectangle = new Rect();
    Window window = mActivity.getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

    ll.setMinimumWidth((int) (displayRectangle.width() * 0.9f));
    ll.setMinimumHeight((int) (displayRectangle.height() * 0.8f));

    webview.getSettings().setJavaScriptEnabled(true);
    try {/*w ww  .  j  a  v  a  2s.c o  m*/
        String uri = String.format(
                "https://accounts.google.com/o/oauth2/auth?client_id=%s&response_type=%s&redirect_uri=%s&scope=%s",
                URLEncoder.encode(AMEnv.GOOGLE_CLIENT_ID, "UTF-8"), URLEncoder.encode("code", "UTF-8"),
                URLEncoder.encode(AMEnv.GOOGLE_REDIRECT_URI, "UTF-8"),
                URLEncoder.encode(AMEnv.GDRIVE_SCOPE, "UTF-8"));
        webview.loadUrl(uri);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    // This is workaround to show input on some android version.
    webview.requestFocus(View.FOCUS_DOWN);
    webview.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }
    });

    webview.setWebViewClient(new WebViewClient() {
        private boolean authenticated = false;

        @Override
        public void onPageFinished(WebView view, String url) {
            loadingText.setVisibility(View.GONE);
            progressDialog.setVisibility(View.GONE);
            webview.setVisibility(View.VISIBLE);
            if (authenticated == true) {
                return;
            }
            String code = getAuthCodeFromUrl(url);
            String error = getErrorFromUrl(url);
            if (error != null) {
                authCodeReceiveListener.onAuthCodeError(error);
                authenticated = true;
                dismiss();
            }
            if (code != null) {
                authenticated = true;
                authCodeReceiveListener.onAuthCodeReceived(code);
                dismiss();
            }
        }
    });
    return v;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public PeerComponent createBrowserComponent(final Object parent) {
    if (getActivity() == null) {
        return null;
    }/*from w  w  w  . j  av a2  s . co  m*/
    final AndroidImplementation.AndroidBrowserComponent[] bc = new AndroidImplementation.AndroidBrowserComponent[1];
    final Throwable[] error = new Throwable[1];
    final Object lock = new Object();

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {

            synchronized (lock) {
                try {
                    WebView wv = new WebView(getActivity()) {

                        public boolean onKeyDown(int keyCode, KeyEvent event) {
                            switch (keyCode) {
                            case KeyEvent.KEYCODE_BACK:
                                Display.getInstance().keyPressed(AndroidImplementation.DROID_IMPL_KEY_BACK);
                                return true;
                            case KeyEvent.KEYCODE_MENU:
                                //if the native commands are used don't handle the keycode
                                if (Display.getInstance()
                                        .getCommandBehavior() != Display.COMMAND_BEHAVIOR_NATIVE) {
                                    Display.getInstance().keyPressed(AndroidImplementation.DROID_IMPL_KEY_MENU);
                                    return true;
                                }
                            }
                            return super.onKeyDown(keyCode, event);
                        }

                        public boolean onKeyUp(int keyCode, KeyEvent event) {
                            switch (keyCode) {
                            case KeyEvent.KEYCODE_BACK:
                                Display.getInstance().keyReleased(AndroidImplementation.DROID_IMPL_KEY_BACK);
                                return true;
                            case KeyEvent.KEYCODE_MENU:
                                //if the native commands are used don't handle the keycode
                                if (Display.getInstance()
                                        .getCommandBehavior() != Display.COMMAND_BEHAVIOR_NATIVE) {
                                    Display.getInstance().keyPressed(AndroidImplementation.DROID_IMPL_KEY_MENU);
                                    return true;
                                }
                            }
                            return super.onKeyUp(keyCode, event);
                        }
                    };
                    wv.setOnTouchListener(new View.OnTouchListener() {

                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                            case MotionEvent.ACTION_UP:
                                if (!v.hasFocus()) {
                                    v.requestFocus();
                                }
                                break;
                            }
                            return false;
                        }
                    });
                    wv.getSettings().setDomStorageEnabled(true);
                    wv.requestFocus(View.FOCUS_DOWN);
                    wv.setFocusableInTouchMode(true);
                    bc[0] = new AndroidImplementation.AndroidBrowserComponent(wv, getActivity(), parent);
                    lock.notify();
                } catch (Throwable t) {
                    error[0] = t;
                    lock.notify();
                }
            }
        }
    });
    while (bc[0] == null && error[0] == null) {
        Display.getInstance().invokeAndBlock(new Runnable() {
            public void run() {
                synchronized (lock) {
                    if (bc[0] == null && error[0] == null) {
                        try {
                            lock.wait(20);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }

        });
    }
    if (error[0] != null) {
        throw new RuntimeException(error[0]);
    }
    return bc[0];
}