Hide keypad in android while touching outside Edit Text Area

后端 未结 3 2235
失恋的感觉
失恋的感觉 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:28

    Code to dismiss Softkeyboard is below:

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

    You can put it in Utility Class or if you are defining it within an activity, avoid the activity parameter, or call hideSoftKeyboard(this).

    You can write a method that iterates through every View in your activity, and check if it is an instanceof EditText if it is not register a setOnTouchListener to that component and everything will fall in place. In case you are wondering how to do that, it is in fact quite simple. Here is what you do, you write a recursive method like the following.

    public void setupUI(View view) {
    
        //Set up touch listener for non-text box views to hide keyboard.
        if(!(view instanceof EditText)) {
    
            view.setOnTouchListener(new OnTouchListener() {
    
                public boolean onTouch(View v, MotionEvent event) {
                    hideSoftKeyboard();
                    return false;
                }
    
            });
        }
    
        //If a layout container, iterate over children and seed recursion.
        if (view instanceof ViewGroup) {
    
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
    
                View innerView = ((ViewGroup) view).getChildAt(i);
    
                setupUI(innerView);
            }
        }
    }
    

    Call this method after SetcontentView() with paramet as id of your view like:

    RelativeLayoutPanel android:id="@+id/parent"> ... 
    

    Then call setupUI(findViewById(R.id.parent))

提交回复
热议问题