Android点击空白区域,隐藏输入法软键盘

很多时候,我们在使用应用时,会出现输入法软键盘弹出的问题,通常情况下,我们默认会使用户点击返回键或者下一步对软键盘进行隐藏。为了更好的体验,我们可以实现当用户使用完毕软键盘时。点击空白区域即可实现隐藏的功能。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getWindow().getDecorView();
            if(isShouldHideSoftInput(view,ev.getX(),ev.getY())){
                hideSoftInput();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void hideSoftInput() {
        View view = this.getCurrentFocus();
        if(view!=null){
            IBinder ib = view.getWindowToken();
            if(ib!=null){
                InputMethodManager im = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                if(im.isActive()){
                    im.hideSoftInputFromWindow(ib, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
    }


    public boolean isShouldHideSoftInput(View view,float x,float y){
        boolean shouldHide = true;
        if(isDownView(view,x,y)){
            if(view instanceof ViewGroup){
                ViewGroup viewGroup = (ViewGroup)view;
                for(int i = 0;i<viewGroup.getChildCount();i++){
                    shouldHide = isShouldHideSoftInput(viewGroup.getChildAt(i),x,y);
                    if(!shouldHide){
                        break;
                    }
                }
            }else{
                if(view instanceof EditText||view instanceof AppCompatEditText){
                    shouldHide  = false;
                }
            }
        }
        return shouldHide;
    }

    public boolean isDownView(View view,float x,float y){
        boolean thisView = false;
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int xl = location[0];
        int yl = location[1];
        if(x>xl&&x<xl+view.getWidth()&&y>yl&&y<yl+view.getHeight()){
            thisView = true;
        }
        return thisView;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值