EditText获取和失去焦点,软键盘的关闭,和软键盘的显示和隐藏的监听

软键盘显示和隐藏的监听:

注: mReplayRelativeLayout是EditText的父布局
 //监听软键盘是否显示或隐藏
        mReplayRelativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect r = new Rect();
                        mReplayRelativeLayout.getWindowVisibleDisplayFrame(r);
                        int screenHeight = mReplayRelativeLayout.getRootView()
                                .getHeight();
                        int heightDifference = screenHeight - (r.bottom);
                        if (heightDifference > 200) {
                            //软键盘显示
// changeKeyboardHeight(heightDifference);
                        } else {
                            //软键盘隐藏

                        }
                    }

                });

点击一个控件使EditText获取焦点并弹出软键盘:
在该控件的点击事件中写以下代码:

                mEditText.setFocusable(true);
                mEditText.setFocusableInTouchMode(true);
                mEditText.requestFocus();
                mEditText.findFocus();
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(mEditText, InputMethodManager.SHOW_FORCED);// 显示输入法

软键盘的隐藏方法一:

注:该方法其实是如果软键盘隐藏的状态这打开软键盘,反之着相反。

  InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

软键盘的隐藏方法二:

注:推荐使用这个

 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);

 

 

 

EditText让其在刚进页面的时候不被选中(不处于焦点状态):

解决办法:

            在EditText的父布局的xml文件中把焦点占据,写一下代码:

            

android:focusable="true"
android:focusableInTouchMode="true"

 

注:点击EditText后使其获取焦点并弹出软件盘,推荐使用setOnTouchListener监听:

  mReplayEditText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mReplayEditText.setFocusable(true);
                mReplayEditText.setFocusableInTouchMode(true);
                return false;
            }

        });

 

posted @ 2017-01-05 11:27  Egg丶牛皮  阅读(37397)  评论(0编辑  收藏  举报