The best way to hide your keyboard on Android

I would like to know how best to hide the keyboard after entering text in EditText.

1) setonfocuschangelistener: only this listener is called when the "Finish" button is pressed or when the focus changes from one EditText to another? When I used this method, I could not hide the keyboard.

2) setOnTouchListener: When I used this, I could hide the keyboard, but I doubt there might be a problem with this. In this case, I add a touch listener to the root LinearLayout. The following code I used:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    txtUserName = (EditText)findViewById(R.id.txtUserName);
    btnLogin = (Button)findViewById(R.id.btnLogin);
    layoutView = (LinearLayout)findViewById(R.id.li);

    layoutView.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(txtUserName
                    .getWindowToken(), 0);
            return true;
        }
    });
}

LinearLayout LinearLayouts. , , , , , . , , (TextView). TextView (.. ), .

, touchListener ? ?

+5
5

InputMethodManager imm = 
    (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditView.getWindowToken(), 0);
+14

:

:

public static void hideSoftKeyboard(Activity activity) {
  InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
  inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

, :

@Override
public boolean onTouchEvent(MotionEvent event) {
 hideSoftKeyboard(LoginActivity.this);
 return false;
}

, .

+9

:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

, edittext.

 inputManager.hideSoftInputFromWindow(editView.getWindowToken(), 0);
+5

null try-catch NullPointerException, .

public void hideKeyboard(Activity activity) {
    InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null) {
            inputManager.hideSoftInputFromWindow(activity.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
}
+2

, dispatchDoneKey . , .

public void dispatchDoneKey() {
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
}
-1

All Articles