工作日志记录:模仿头条的评论功能输入框控制输入法并完整实现软键盘的在此环境下的UE控制

工作日志记录:项目中有个需求是要实现类似于头条那样的评论功能,当点击EditText的时候弹出软键盘并输入评论之后点击发送功能然后隐藏软键盘,和eidttext对应的输入框

实现思路:首先实现这个功能的时候需要让edittext去控制软件盘的弹起和收起动作。,其次是点击发送按钮之后要让键盘收起。


具体代码如下:

edittext和发送按钮的父控件LInearlayout监听软件盘的收起和弹出动作来控制自己的显示与隐藏:

 //监听软键盘是否显示或隐藏
        ll_inputmethod.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect r = new Rect();
                        ll_inputmethod.getWindowVisibleDisplayFrame(r);
                        int screenHeight = ll_inputmethod.getRootView()
                                .getHeight();
                        int heightDifference = screenHeight - (r.bottom);
//                        Toast.makeText(activity, "heightDiff"+heightDifference, Toast.LENGTH_SHORT).show();
                        if (heightDifference > 200) {
                            //软键盘显示
                            ll_inputmethod.setVisibility(View.VISIBLE);
                        } else {
                            //软键盘隐藏
                            ll_inputmethod.setVisibility(View.GONE);
                        }
                        edit_comment.setText("");//初始化操作
                    }

                });

当点击评论按钮之后或者点击显示edittext时,弹出软键盘:(当传入的hideOrNot值为 true时,表示此时需要控制软件盘隐藏,由于上一个方法中通过监听软件盘的动作控制了父控件的显示和隐藏,所以结合这两个方法可以看出软键盘和父控件在这里做到了相互影响的效果)

/**
     * EditText获取焦点并显示软键盘
     */
    public  void showSoftInputFromWindow(Activity activity, EditText editText,boolean hideOrNot) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
//        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //打开软键盘
        InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if(hideOrNot){
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }else{
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

当点击返回键的时候,有可能当前的软键盘还是弹起的,如果不做处理的话,会返回前一个界面,但是软键盘没有隐藏,此时需要做如下处理(第二个判断):

public void setOnClickBarck() {
    if (v_image_watcher.isShown()) {
        v_image_watcher.handleBackPressed();
    }else if(ll_inputmethod.getVisibility()==View.VISIBLE){
        showSoftInputFromWindow(activity,edit_comment,true);
    } else {
        activity.finish();
        if(isCanelCollect){
            EventBus.getDefault().post(new EventBusCancleCollect(true));
        }
    }
}



猜你喜欢

转载自blog.csdn.net/always_myhometown/article/details/78455865