关于软键盘不得不记录的事

来源:互联网 发布:四大工资2017 知乎 编辑:程序博客网 时间:2024/06/05 10:37
大家在做搜索功能的时候一个很常见的需求就是跳转到搜索页面时自动弹出软键盘,恩,这很简单,网上也有很多资料:
edittext.setFocusable(true);    
edittext.setFocusableInTouchMode(true);    
edittext.requestFocus();
 forcetoggleSoftInput(edittext);
public void forcetoggleSoftInput(EditText edittext){
Timer timer = new Timer(); //设置定时器
timer.schedule(new TimerTask() {
    @Override
    public void run() { //弹出软键盘的代码
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(edittext, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_SHOWN,InputMethodManager.HIDE_NOT_ALWAYS);
    }
}, 300);
}
做完这一切都没问题,软键盘能正常弹出,但是为了用户更好的体验我们需要在点击空白处时让软键盘消失,这也好说,上代码:
public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View x = getCurrentFocus();
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null && isShouldHideInput(x, ev)) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }


        }
        return super.dispatchTouchEvent(ev);
    }
这在之前屡试不爽的代码在强制弹出软键盘后居然失效了,在一顿疯狂查阅资料之后,尝试将InputMethodManager.HIDE_NOT_ALWAYS改为InputMethodManager.RESULT_UNCHANGED_SHOWN之后成功了,好吧,不要问我为什么,我也不知道,在此提供一下可能遇到这种情况的解决办法。

                                             
0 0
原创粉丝点击