Example usage for android.view View requestFocus

List of usage examples for android.view View requestFocus

Introduction

In this page you can find the example usage for android.view View requestFocus.

Prototype

public final boolean requestFocus() 

Source Link

Document

Call this to try to give focus to a specific view or to one of its descendants.

Usage

From source file:com.quarterfull.newsAndroid.LoginDialogFragment.java

/**
 * Attempts to sign in or register the account specified by the login form.
 * If there are form errors (invalid email, missing fields, etc.), the
 * errors are presented and no actual login attempt is made.
 *//*from ww w.j a  va  2s.  c om*/
public void attemptLogin() {
    if (mAuthTask != null) {
        return;
    }

    // Reset errors.
    mUsernameView.setError(null);
    mPasswordView.setError(null);
    mOc_root_path_View.setError(null);

    // Store values at the time of the login attempt.
    mUsername = mUsernameView.getText().toString().trim();
    mPassword = mPasswordView.getText().toString();
    mOc_root_path = mOc_root_path_View.getText().toString().trim();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password.
    if (TextUtils.isEmpty(mPassword)) {
        mPasswordView.setError(getString(R.string.error_field_required));
        focusView = mPasswordView;
        cancel = true;
    }
    // Check for a valid email address.
    if (TextUtils.isEmpty(mUsername)) {
        mUsernameView.setError(getString(R.string.error_field_required));
        focusView = mUsernameView;
        cancel = true;
    }

    if (TextUtils.isEmpty(mOc_root_path)) {
        mOc_root_path_View.setError(getString(R.string.error_field_required));
        focusView = mOc_root_path_View;
        cancel = true;
    } else {
        try {
            URL url = new URL(mOc_root_path);
            if (!url.getProtocol().equals("https"))
                ShowAlertDialog(getString(R.string.login_dialog_title_security_warning),
                        getString(R.string.login_dialog_text_security_warning), getActivity());
        } catch (MalformedURLException e) {
            mOc_root_path_View.setError(getString(R.string.error_invalid_url));
            focusView = mOc_root_path_View;
            cancel = true;
            //e.printStackTrace();
        }
    }

    if (cancel) {
        // There was an error; don't attempt login and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        mAuthTask = new UserLoginTask(mUsername, mPassword, mOc_root_path);
        mAuthTask.execute((Void) null);

        mDialogLogin = BuildPendingDialogWhileLoggingIn();
        mDialogLogin.show();
    }
}

From source file:ael.com.loterias.c_login.java

public void PRC_INTENTAR_LOGIN() throws IOException {

    // Quitamos los campos de registro de usuario
    mRetypePasswordView = (EditText) findViewById(R.id.retype_password);
    mButtonRegister = (Button) findViewById(R.id.register_button);

    mRetypePasswordView.setVisibility(View.INVISIBLE);
    mButtonRegister.setText(R.string.st_la_Register);

    // Si el check est pinchado recordar en las preferences
    PRC_RECORDAR_MAIL_PASSWORD();/*ww  w.j a  v  a  2 s .  c  om*/

    // Reset errors.
    mEmailView.setError(null);
    mPasswordView.setError(null);

    // Store values at the time of the login attempt.
    mEmail = mEmailView.getText().toString();
    mPassword = mPasswordView.getText().toString();

    boolean cancel = false;
    View focusView = null;

    // Check for a valid password.
    if (TextUtils.isEmpty(mPassword)) {
        mPasswordView.setError(getString(R.string.st_la_Field_Required));
        focusView = mPasswordView;
        cancel = true;
    } else if (mPassword.length() < c_login.LENGTH_PASSWORD) {
        mPasswordView.setError(getString(R.string.st_la_Invalid_Password));
        focusView = mPasswordView;
        cancel = true;
    }

    // Check for a valid email address.
    if (TextUtils.isEmpty(mEmail)) {
        mEmailView.setError(getString(R.string.st_la_Field_Required));
        focusView = mEmailView;
        cancel = true;
    } else if (!mEmail.contains("@")) {
        mEmailView.setError(getString(R.string.st_la_Invalid_Email));
        focusView = mEmailView;
        cancel = true;
    }

    if (cancel) {
        // There was an error; don't attempt login and focus the first
        // form field with an error.
        focusView.requestFocus();
    } else {
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.

        c_logging.getInstance().log(c_logging.LOG_INFO, "Lanzamos InitTask");

        c_PGP_RSA RSA = new c_PGP_RSA();
        RSA.inicio();

        /*
                    // Generamos la clave pblica y privada
                    // Consultar las preferencias
                    Context context = getApplicationContext();
                    c_preferences appPrefs = new c_preferences(context);
                
                    //if (appPrefs.getExistsRSAKEY()) {
        // Existen las claves no las vuelvo a generar
        c_logging.getInstance().log(c_logging.LOG_INFO, "PGP Las claves YA EXISTEN" );
                
                    //} else {
        // No existen, las vuelvo a generar
        c_logging.getInstance().log(c_logging.LOG_INFO, "PGP Las claves no existen ... se vuelven a generar" );
                
        c_PGP_KeyGenerator cPGP = new c_PGP_KeyGenerator(context);
        cPGP.generateKeys();
                
        // Almaceno las claves en el almacn
        appPrefs.setPrivateKEY_APPLICATION(cPGP.getPrivateKeyAsString());
        appPrefs.setPublicKEY_APPLICATION(cPGP.getPublicKeyAsString());
                
                
                    //}
                
                
                    String EncryptedText = cPGP.encrypt(cPGP.getPublicKey(), "hola");
                    c_logging.getInstance().log(c_logging.LOG_INFO, "Encrypted  : " + EncryptedText );
                
                    try {
        String DecryptedText = cPGP.decrypt(cPGP.getPrivateKey(), EncryptedText);
        c_logging.getInstance().log(c_logging.LOG_INFO, "Decrypted  : " + DecryptedText);
                    } catch (Exception e) {
        e.printStackTrace();
                    }
                    // Anulado temporalmente
                    //PRC_CARGAR_LOGIN_TASK(context, getString(R.string.st_la_Check_Connection_Thinking), getString(R.string.STR_INFO_OPERATION_FUNCTION_APP_LOGIN));
                */
    }
}

From source file:com.meetingninja.csse.user.RegisterActivity.java

private void tryRegister() {
    // Reset errors
    nameText.setError(null);/*from  www  .  j av  a  2 s . c om*/
    emailText.setError(null);
    passwordText.setError(null);
    confirmPasswordText.setError(null);

    // Store values
    String name = nameText.getText().toString().trim();
    String email = emailText.getText().toString().trim();
    String pass = passwordText.getText().toString().trim();
    String confPass = confirmPasswordText.getText().toString().trim();

    Log.d("Registering", name + " : " + email + " : " + pass + " : " + confPass);

    boolean cancel = false;
    View focusView = null;

    if (TextUtils.isEmpty(confPass)) {
        confirmPasswordText.setError(getString(R.string.error_field_required));
        focusView = confirmPasswordText;
        cancel = true;
    } else if (!confPass.equals(pass)) {
        Log.e("PASS_MISMATCH", "error");
        confirmPasswordText.setError(getString(R.string.error_mismatch_password));
        focusView = confirmPasswordText;
        cancel = true;
    } else if (confPass.length() < 4) {
        confirmPasswordText.setError(getString(R.string.error_invalid_password));
        focusView = confirmPasswordText;
        cancel = true;
    }
    if (TextUtils.isEmpty(pass)) {
        passwordText.setError(getString(R.string.error_field_required));
        focusView = passwordText;
        cancel = true;
    } else if (pass.length() < 4) {
        passwordText.setError(getString(R.string.error_field_required));
        focusView = passwordText;
        cancel = true;
    }
    if (TextUtils.isEmpty(email)) {
        emailText.setError(getString(R.string.error_field_required));
        focusView = emailText;
        cancel = true;
    } else if (!Utilities.isValidEmailAddress(email)) {
        emailText.setError(getString(R.string.error_invalid_email));
        focusView = emailText;
        cancel = true;
    }
    if (TextUtils.isEmpty(name)) {
        nameText.setError(getString(R.string.error_field_required));
        focusView = nameText;
        cancel = true;
    }

    if (cancel) {
        focusView.requestFocus();
    } else {
        registerTask = new RegisterTask(this);
        registerTask.execute(name, email, pass);
        // go to process finish
    }

}

From source file:com.libreteam.taxi.Customer_Boarding.java

@SuppressLint("InflateParams")
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*w  ww.  j a v a2 s .  c om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View view = inflater.inflate(R.layout.customer_boarding_, null);
    context = view.getContext();
    isTracking = false;

    ride_id = getArguments().getStringArray("rideid")[0];
    customer_id = getArguments().getStringArray("rideid")[1];
    address = getArguments().getStringArray("rideid")[2];
    latlng = getArguments().getStringArray("rideid")[3];
    car_model = getArguments().getStringArray("rideid")[4];
    time = getArguments().getStringArray("rideid")[5];
    //       username= getArguments().getStringArray("rideid")[6];
    username = Customer_Constants.selected_taxi_appname; //jin
    taxi_company = getArguments().getStringArray("rideid")[7];
    //       license_plate = getArguments().getStringArray("rideid")[8];
    license_plate = Customer_Constants.selected_plate_number;
    //       avatar = getArguments().getStringArray("rideid")[9];
    Taxi_System.testLog(address);

    ArrayList aList = new ArrayList(Arrays.asList(latlng.split(",")));
    ArrayList d_aList = new ArrayList(Arrays.asList(getArguments().getStringArray("rideid")[12].split(",")));
    customerLatLng = new LatLng(Double.parseDouble(d_aList.get(0).toString()),
            Double.parseDouble(d_aList.get(1).toString()));
    driverLatLng = new LatLng(Double.parseDouble(aList.get(0).toString()),
            Double.parseDouble(aList.get(1).toString()));

    if (savedInstanceState == null)
        initComponents(view);

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (((Customer_Fragment_Activity) getActivity()).isMenu) {
                    ((Customer_Fragment_Activity) getActivity()).didHideMenu();
                    return true;
                }
                didRejectRide();
                ((Customer_Fragment_Activity) getActivity()).didFinish();
                return true;
            } else
                return false;
        }
    });
    return view;
}

From source file:com.aviary.android.feather.sdk.widget.AviaryWorkspace.java

private void onFinishedAnimation(int newScreen) {

    final int previousScreen = mCurrentScreen;

    final boolean toLeft = newScreen > mCurrentScreen;
    final boolean toRight = newScreen < mCurrentScreen;
    final boolean changed = newScreen != mCurrentScreen;

    mCurrentScreen = newScreen;/*from   ww w  .  j  av  a  2  s .  co m*/
    if (mIndicator != null)
        mIndicator.setLevel(mCurrentScreen, mItemCount);
    setNextSelectedPositionInt(INVALID_SCREEN);

    fillToGalleryRight();
    fillToGalleryLeft();

    if (toLeft) {
        detachOffScreenChildren(true);
    } else if (toRight) {
        detachOffScreenChildren(false);
    }

    if (changed || mItemCount == 1 || true) {

        View child = getChildAt(mCurrentScreen - mFirstPosition);

        if (null != child) {
            if (mAllowChildSelection) {

                if (null != mOldSelectedChild) {
                    mOldSelectedChild.setSelected(false);
                    mOldSelectedChild = null;
                }

                child.setSelected(true);
                mOldSelectedChild = child;
            }
            child.requestFocus();
        }
    }

    clearChildrenCache();

    if (mOnPageChangeListener != null && newScreen != mPreviousScreen) {
        post(new Runnable() {

            @Override
            public void run() {

                if (null != mOnPageChangeListener)
                    mOnPageChangeListener.onPageChanged(mCurrentScreen, previousScreen);
            }
        });
    }

    postUpdateIndicator(mCurrentScreen, mItemCount);

    mPreviousScreen = newScreen;
}

From source file:org.connectbot.ConsoleActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        StrictModeSetup.run();//  ww  w . j av a  2  s . c om
    }

    hardKeyboard = getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY;

    clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    titleBarHide = prefs.getBoolean(PreferenceConstants.TITLEBARHIDE, false);
    if (titleBarHide && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // This is a separate method because Gradle does not uniformly respect the conditional
        // Build check. See: https://code.google.com/p/android/issues/detail?id=137195
        requestActionBar();
    }

    this.setContentView(R.layout.act_console);

    // hide status bar if requested by user
    if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false)) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    // TODO find proper way to disable volume key beep if it exists.
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // handle requested console from incoming intent
    if (icicle == null) {
        requested = getIntent().getData();
    } else {
        String uri = icicle.getString(STATE_SELECTED_URI);
        if (uri != null) {
            requested = Uri.parse(uri);
        }
    }

    inflater = LayoutInflater.from(this);

    toolbar = (Toolbar) findViewById(R.id.toolbar);

    pager = (TerminalViewPager) findViewById(R.id.console_flip);
    pager.addOnPageChangeListener(new TerminalViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            setTitle(adapter.getPageTitle(position));
            onTerminalChanged();
        }
    });
    adapter = new TerminalPagerAdapter();
    pager.setAdapter(adapter);

    empty = (TextView) findViewById(android.R.id.empty);

    stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group);
    stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions);
    stringPrompt = (EditText) findViewById(R.id.console_password);
    stringPrompt.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP)
                return false;
            if (keyCode != KeyEvent.KEYCODE_ENTER)
                return false;

            // pass collected password down to current terminal
            String value = stringPrompt.getText().toString();

            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return false;
            helper.setResponse(value);

            // finally clear password for next user
            stringPrompt.setText("");
            updatePromptVisible();

            return true;
        }
    });

    booleanPromptGroup = (RelativeLayout) findViewById(R.id.console_boolean_group);
    booleanPrompt = (TextView) findViewById(R.id.console_prompt);

    booleanYes = (Button) findViewById(R.id.console_prompt_yes);
    booleanYes.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return;
            helper.setResponse(Boolean.TRUE);
            updatePromptVisible();
        }
    });

    Button booleanNo = (Button) findViewById(R.id.console_prompt_no);
    booleanNo.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return;
            helper.setResponse(Boolean.FALSE);
            updatePromptVisible();
        }
    });

    fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed);

    // Preload animation for keyboard button
    keyboard_fade_in = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_in);
    keyboard_fade_out = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_out);

    keyboardGroup = (LinearLayout) findViewById(R.id.keyboard_group);

    keyboardAlwaysVisible = prefs.getBoolean(PreferenceConstants.KEY_ALWAYS_VISIVLE, false);
    if (keyboardAlwaysVisible) {
        // equivalent to android:layout_above=keyboard_group
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.addRule(RelativeLayout.ABOVE, R.id.keyboard_group);
        pager.setLayoutParams(layoutParams);

        // Show virtual keyboard
        keyboardGroup.setVisibility(View.VISIBLE);
    }

    mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard);
    mKeyboardButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View terminal = adapter.getCurrentTerminalView();
            if (terminal == null)
                return;
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInputFromWindow(terminal.getApplicationWindowToken(),
                    InputMethodManager.SHOW_FORCED, 0);
            terminal.requestFocus();
            hideEmulatedKeys();
        }
    });

    findViewById(R.id.button_ctrl).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_esc).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_tab).setOnClickListener(emulatedKeysListener);

    addKeyRepeater(findViewById(R.id.button_up));
    addKeyRepeater(findViewById(R.id.button_up));
    addKeyRepeater(findViewById(R.id.button_down));
    addKeyRepeater(findViewById(R.id.button_left));
    addKeyRepeater(findViewById(R.id.button_right));

    findViewById(R.id.button_home).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_end).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_pgup).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_pgdn).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f1).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f2).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f3).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f4).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f5).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f6).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f7).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f8).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f9).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f10).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f11).setOnClickListener(emulatedKeysListener);
    findViewById(R.id.button_f12).setOnClickListener(emulatedKeysListener);

    actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        if (titleBarHide) {
            actionBar.hide();
        }
        actionBar.addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() {
            public void onMenuVisibilityChanged(boolean isVisible) {
                inActionBarMenu = isVisible;
                if (!isVisible) {
                    hideEmulatedKeys();
                }
            }
        });
    }

    final HorizontalScrollView keyboardScroll = (HorizontalScrollView) findViewById(R.id.keyboard_hscroll);
    if (!hardKeyboard) {
        // Show virtual keyboard and scroll back and forth
        showEmulatedKeys(false);
        keyboardScroll.postDelayed(new Runnable() {
            @Override
            public void run() {
                final int xscroll = findViewById(R.id.button_f12).getRight();
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "smoothScrollBy(toEnd[" + xscroll + "])");
                }
                keyboardScroll.smoothScrollBy(xscroll, 0);
                keyboardScroll.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (BuildConfig.DEBUG) {
                            Log.d(TAG, "smoothScrollBy(toStart[" + (-xscroll) + "])");
                        }
                        keyboardScroll.smoothScrollBy(-xscroll, 0);
                    }
                }, 500);
            }
        }, 500);
    }

    // Reset keyboard auto-hide timer when scrolling
    keyboardScroll.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                autoHideEmulatedKeys();
                break;
            case MotionEvent.ACTION_UP:
                v.performClick();
                return (true);
            }
            return (false);
        }
    });

    tabs = (TabLayout) findViewById(R.id.tabs);
    if (tabs != null)
        setupTabLayoutWithViewPager();

    pager.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showEmulatedKeys(true);
        }
    });

    // Change keyboard button image according to soft keyboard visibility
    // How to detect keyboard visibility: http://stackoverflow.com/q/4745988
    contentView = findViewById(android.R.id.content);
    contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Rect r = new Rect();
            contentView.getWindowVisibleDisplayFrame(r);
            int screenHeight = contentView.getRootView().getHeight();
            int keypadHeight = screenHeight - r.bottom;

            if (keypadHeight > screenHeight * 0.15) {
                // keyboard is opened
                mKeyboardButton.setImageResource(R.drawable.ic_keyboard_hide);
                mKeyboardButton.setContentDescription(
                        getResources().getText(R.string.image_description_hide_keyboard));
            } else {
                // keyboard is closed
                mKeyboardButton.setImageResource(R.drawable.ic_keyboard);
                mKeyboardButton.setContentDescription(
                        getResources().getText(R.string.image_description_show_keyboard));
            }
        }
    });
}

From source file:com.jzh.stuapp.view.MyViewPager.java

public boolean arrowScroll(int direction) {
    View currentFocused = findFocus();
    if (currentFocused == this)
        currentFocused = null;/* w  w  w  . j  a v  a 2s  .c o  m*/

    boolean handled = false;

    View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
    if (nextFocused != null && nextFocused != currentFocused) {
        if (direction == View.FOCUS_LEFT) {
            if (currentFocused != null && nextFocused.getLeft() >= currentFocused.getLeft()) {
                handled = pageLeft();
            } else {
                handled = nextFocused.requestFocus();
            }
        } else if (direction == View.FOCUS_RIGHT) {
            if (currentFocused != null && nextFocused.getLeft() <= currentFocused.getLeft()) {
                handled = pageRight();
            } else {
                handled = nextFocused.requestFocus();
            }
        }
    } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {
        handled = pageLeft();
    } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {
        handled = pageRight();
    }
    if (handled) {
        playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
    }
    return handled;
}

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 {//from  www. j a  v  a 2s . c om
        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:org.mozilla.gecko.home.BrowserSearch.java

private void showSuggestionsOptIn() {
    // Return if the ViewStub was already inflated - an inflated ViewStub is removed from the
    // View hierarchy so a second call to findViewById will return null.
    if (mSuggestionsOptInPrompt != null) {
        return;/*from   w  ww. j a  va2s .co m*/
    }

    mSuggestionsOptInPrompt = ((ViewStub) mView.findViewById(R.id.suggestions_opt_in_prompt)).inflate();

    TextView promptText = (TextView) mSuggestionsOptInPrompt.findViewById(R.id.suggestions_prompt_title);
    promptText.setText(getResources().getString(R.string.suggestions_prompt));

    final View yesButton = mSuggestionsOptInPrompt.findViewById(R.id.suggestions_prompt_yes);
    final View noButton = mSuggestionsOptInPrompt.findViewById(R.id.suggestions_prompt_no);

    final OnClickListener listener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Prevent the buttons from being clicked multiple times (bug 816902)
            yesButton.setOnClickListener(null);
            noButton.setOnClickListener(null);

            setSuggestionsEnabled(v == yesButton);
        }
    };

    yesButton.setOnClickListener(listener);
    noButton.setOnClickListener(listener);

    // If the prompt gains focus, automatically pass focus to the
    // yes button in the prompt.
    final View prompt = mSuggestionsOptInPrompt.findViewById(R.id.prompt);
    prompt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                yesButton.requestFocus();
            }
        }
    });
}