Hide keypad in android while touching outside Edit Text Area

后端 未结 3 2220
失恋的感觉
失恋的感觉 2021-02-20 10:50

I know that the code for dismiss tyhe keypad in android is

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hide         


        
3条回答
  •  你的背包
    2021-02-20 11:21

    This may be old but I got this working by implenting a custom class

    public class DismissKeyboardListener implements OnClickListener { 
    
        Activity mAct;
    
        public DismissKeyboardListener(Activity act) {
            this.mAct = act;
        } 
    
        @Override 
        public void onClick(View v) {
            if ( v instanceof ViewGroup ) {
                hideSoftKeyboard( this.mAct );
            } 
        }        
    } 
    
    public void hideSoftKeyboard(Activity activity) {
            InputMethodManager imm = (InputMethodManager)
            getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    } 
    

    the best practice here is to create a Helper class and every container Relative / Linear Layouts should implement this.

    **** Take note only the main Container should implement this class (For optimization) ****

    and implement it like this :

    Parent.setOnClickListener( new DismissKeyboardListener(this) ); 
    

    the keyword this is for Activity. so if you are on fragment you use it like getActivity();

    ---thumbs up if it help you... --- cheers Ralph ---

提交回复
热议问题