Code example for View

Methods: findViewById, isFocused, requestFocus, setOnFocusChangeListener

0
    /** 
     * @param editViewId must be EditView 
     */ 
    public void requestFocusAndShowKeyboard(int editViewId) {
        // Set Focus to password View. 
        final View viewToBeFocused = mView.findViewById(editViewId);
        if (viewToBeFocused == null) {
            Log.w(TAG, "password field to be focused not found.");
        } else if (!(viewToBeFocused instanceof EditText)) {
            Log.w(TAG, "password field is not EditText");
        } else { 
            if (viewToBeFocused.isFocused()) {
                Log.i(TAG, "Already focused");
                if (!mInputMethodManager.showSoftInput(viewToBeFocused, 0)) {
                    Log.w(TAG, "Failed to show SoftInput");
                } 
            } else { 
                // After acquiring the focus, we show software keyboard. 
                viewToBeFocused.setOnFocusChangeListener(this);
                final boolean requestFocusResult = viewToBeFocused.requestFocus();
                Log.i(TAG, String.format("Focus request: %s",
                        (requestFocusResult ? "successful" : "failed")));
                if (!requestFocusResult) {
                    viewToBeFocused.setOnFocusChangeListener(null);
                } 
            } 
        } 
    }