当用户点击android中屏幕上的任何其他位置时隐藏键盘

时间:2022-12-01 14:15:55

I need to hide the softkeypad in android when user click on anywhere other than a Edittext. There are many help for iphone but not for android. I tried this code but its not working :(

当用户点击Edittext以外的任何地方时,我需要在android中隐藏softkeypad。 iphone有很多帮助,但不适用于android。我试过这段代码,但它无法正常工作:(

final RelativeLayout base = (RelativeLayout) findViewById(R.id.RelativeLayout1);

    findViewById(R.id.base).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(base.getWindowToken(), 0);

        }
    });

Thanks in advance !

提前致谢 !

6 个解决方案

#1


52  

You can use the onTouchEvent() to hide the Softkeyboard.

您可以使用onTouchEvent()来隐藏软键盘。

@Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.
                                                        INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        return true;
    }

Though this solution works, but the best I would suggest is to use below answer as it gives best solution of closing the keyboard touching anywhere else then EditText.

虽然这个解决方案有效,但我建议最好使用下面的答案,因为它提供了关闭键盘触摸其他任何地方然后EditText的最佳解决方案。

#2


24  

Well I have done this way:

我这样做了:

Add code in your Activity.

在您的活动中添加代码。

This would work for Fragment also, no need to add this code in Fragment.

这也适用于Fragment,无需在Fragment中添加此代码。

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View view = getCurrentFocus();
    if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        view.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + view.getLeft() - scrcoords[0];
        float y = ev.getRawY() + view.getTop() - scrcoords[1];
        if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
        ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
    }
    return super.dispatchTouchEvent(ev);
}

Hope this will help you.

希望这会帮助你。

#3


13  

The best work around I found was using as below,

我找到的最好的工作是使用如下,

Override dispatchTouchEvent() and try to get the area of EditText using Rect

覆盖dispatchTouchEvent()并尝试使用Rect获取EditText的区域

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
         int x = (int) ev.getX();
         int y = (int) ev.getY();

         if (ev.getAction() == MotionEvent.ACTION_DOWN &&
             !getLocationOnScreen(etFeedback).contains(x, y)) {
             InputMethodManager input = (InputMethodManager) 
                                   activity.getSystemService(Context.INPUT_METHOD_SERVICE);
             input.hideSoftInputFromWindow(etFeedback.getWindowToken(), 0);
         }

        return super.dispatchTouchEvent(ev);
    }

Method that caculates 4 corner of View(here its EditText)

计算View的4个角的方法(这里是EditText)

protected Rect getLocationOnScreen(EditText mEditText) {
        Rect mRect = new Rect();
        int[] location = new int[2];

        mEditText.getLocationOnScreen(location);

        mRect.left = location[0];
        mRect.top = location[1];
        mRect.right = location[0] + mEditText.getWidth();
        mRect.bottom = location[1] + mEditText.getHeight();

        return mRect;
    }

By using above code we can detect the area of EditText and we can check if the touch on the screen is part of the area of EditText or not. If its part of EditText then don't do anything let the touch do its job, and if the touch doesn't contain area of EditText then just close the softkeyboard.

通过使用上面的代码,我们可以检测EditText的区域,我们可以检查屏幕上的触摸是否是EditText区域的一部分。如果它的EditText部分没有做任何事情让触摸完成它的工作,如果触摸不包含EditText的区域,那么只需关闭软键盘。

******EDIT******

I just found another approach if we don't want to give any EditText as input and want to hide keyboard inside whole application when user touches anywhere else other than EditText. Then you have to create an BaseActivity and write global code for hiding keyboard as below,

我刚刚发现了另一种方法,如果我们不想将任何EditText作为输入,并且当用户触摸除EditText之外的任何其他地方时想要在整个应用程序中隐藏键盘。然后你必须创建一个BaseActivity并编写隐藏键盘的全局代码,如下所示,

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        boolean handleReturn = super.dispatchTouchEvent(ev);

        View view = getCurrentFocus();

         int x = (int) ev.getX();
         int y = (int) ev.getY();

         if(view instanceof EditText){
             View innerView = getCurrentFocus();

             if (ev.getAction() == MotionEvent.ACTION_UP && 
                                    !getLocationOnScreen(innerView).contains(x, y)) {

                 InputMethodManager input = (InputMethodManager) 
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
                 input.hideSoftInputFromWindow(getWindow().getCurrentFocus()
                                                                 .getWindowToken(), 0);
             }
         }

        return handleReturn;
    }

#4


0  

I tried this to hide Keyboard. You need to pass the method in your Layout file.

我试过这个隐藏键盘。您需要在布局文件中传递该方法。

public void setupUI(View view) {
    // Set up touch listener for non-text box views to hide keyboard.
    if (!(view instanceof EditText)) {
        view.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard(LOGSignUpActivity.this);
                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);
        }
    }
}

#5


0  

Call this method in your MainAcitivity.class

在MainAcitivity.class中调用此方法

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

#6


0  

For those who are looking for a Xamarin code for this, here you go :

对于那些正在为此寻找Xamarin代码的人,请转到:

  public override bool DispatchTouchEvent(MotionEvent ev)
    {
        try
        {
            View view = CurrentFocus;
            if (view != null && (ev.Action == MotionEventActions.Up || ev.Action == MotionEventActions.Move) && view is EditText && !view.Class.Name.StartsWith("android.webkit."))
            {
                int[] Touch = new int[2];
                view.GetLocationOnScreen(Touch);
                float x = ev.RawX + view.Left - Touch[0];
                float y = ev.RawY + view.Top - Touch[1];
                if (x < view.Left || x > view.Right || y < view.Top || y > view.Bottom)
                    ((InputMethodManager)GetSystemService(InputMethodService)).HideSoftInputFromWindow((Window.DecorView.ApplicationWindowToken), 0);
            }
        }
        catch (System.Exception ex)
        {

        }

        return base.DispatchTouchEvent(ev);
    }

#1


52  

You can use the onTouchEvent() to hide the Softkeyboard.

您可以使用onTouchEvent()来隐藏软键盘。

@Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.
                                                        INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        return true;
    }

Though this solution works, but the best I would suggest is to use below answer as it gives best solution of closing the keyboard touching anywhere else then EditText.

虽然这个解决方案有效,但我建议最好使用下面的答案,因为它提供了关闭键盘触摸其他任何地方然后EditText的最佳解决方案。

#2


24  

Well I have done this way:

我这样做了:

Add code in your Activity.

在您的活动中添加代码。

This would work for Fragment also, no need to add this code in Fragment.

这也适用于Fragment,无需在Fragment中添加此代码。

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View view = getCurrentFocus();
    if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        view.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + view.getLeft() - scrcoords[0];
        float y = ev.getRawY() + view.getTop() - scrcoords[1];
        if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
        ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
    }
    return super.dispatchTouchEvent(ev);
}

Hope this will help you.

希望这会帮助你。

#3


13  

The best work around I found was using as below,

我找到的最好的工作是使用如下,

Override dispatchTouchEvent() and try to get the area of EditText using Rect

覆盖dispatchTouchEvent()并尝试使用Rect获取EditText的区域

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
         int x = (int) ev.getX();
         int y = (int) ev.getY();

         if (ev.getAction() == MotionEvent.ACTION_DOWN &&
             !getLocationOnScreen(etFeedback).contains(x, y)) {
             InputMethodManager input = (InputMethodManager) 
                                   activity.getSystemService(Context.INPUT_METHOD_SERVICE);
             input.hideSoftInputFromWindow(etFeedback.getWindowToken(), 0);
         }

        return super.dispatchTouchEvent(ev);
    }

Method that caculates 4 corner of View(here its EditText)

计算View的4个角的方法(这里是EditText)

protected Rect getLocationOnScreen(EditText mEditText) {
        Rect mRect = new Rect();
        int[] location = new int[2];

        mEditText.getLocationOnScreen(location);

        mRect.left = location[0];
        mRect.top = location[1];
        mRect.right = location[0] + mEditText.getWidth();
        mRect.bottom = location[1] + mEditText.getHeight();

        return mRect;
    }

By using above code we can detect the area of EditText and we can check if the touch on the screen is part of the area of EditText or not. If its part of EditText then don't do anything let the touch do its job, and if the touch doesn't contain area of EditText then just close the softkeyboard.

通过使用上面的代码,我们可以检测EditText的区域,我们可以检查屏幕上的触摸是否是EditText区域的一部分。如果它的EditText部分没有做任何事情让触摸完成它的工作,如果触摸不包含EditText的区域,那么只需关闭软键盘。

******EDIT******

I just found another approach if we don't want to give any EditText as input and want to hide keyboard inside whole application when user touches anywhere else other than EditText. Then you have to create an BaseActivity and write global code for hiding keyboard as below,

我刚刚发现了另一种方法,如果我们不想将任何EditText作为输入,并且当用户触摸除EditText之外的任何其他地方时想要在整个应用程序中隐藏键盘。然后你必须创建一个BaseActivity并编写隐藏键盘的全局代码,如下所示,

 @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        boolean handleReturn = super.dispatchTouchEvent(ev);

        View view = getCurrentFocus();

         int x = (int) ev.getX();
         int y = (int) ev.getY();

         if(view instanceof EditText){
             View innerView = getCurrentFocus();

             if (ev.getAction() == MotionEvent.ACTION_UP && 
                                    !getLocationOnScreen(innerView).contains(x, y)) {

                 InputMethodManager input = (InputMethodManager) 
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
                 input.hideSoftInputFromWindow(getWindow().getCurrentFocus()
                                                                 .getWindowToken(), 0);
             }
         }

        return handleReturn;
    }

#4


0  

I tried this to hide Keyboard. You need to pass the method in your Layout file.

我试过这个隐藏键盘。您需要在布局文件中传递该方法。

public void setupUI(View view) {
    // Set up touch listener for non-text box views to hide keyboard.
    if (!(view instanceof EditText)) {
        view.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard(LOGSignUpActivity.this);
                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);
        }
    }
}

#5


0  

Call this method in your MainAcitivity.class

在MainAcitivity.class中调用此方法

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

#6


0  

For those who are looking for a Xamarin code for this, here you go :

对于那些正在为此寻找Xamarin代码的人,请转到:

  public override bool DispatchTouchEvent(MotionEvent ev)
    {
        try
        {
            View view = CurrentFocus;
            if (view != null && (ev.Action == MotionEventActions.Up || ev.Action == MotionEventActions.Move) && view is EditText && !view.Class.Name.StartsWith("android.webkit."))
            {
                int[] Touch = new int[2];
                view.GetLocationOnScreen(Touch);
                float x = ev.RawX + view.Left - Touch[0];
                float y = ev.RawY + view.Top - Touch[1];
                if (x < view.Left || x > view.Right || y < view.Top || y > view.Bottom)
                    ((InputMethodManager)GetSystemService(InputMethodService)).HideSoftInputFromWindow((Window.DecorView.ApplicationWindowToken), 0);
            }
        }
        catch (System.Exception ex)
        {

        }

        return base.DispatchTouchEvent(ev);
    }