Android 软键盘踩坑记

最近在开发一个朋友圈产品的时候遇到一个bug:软键盘遮罩,在解决的过程当中我经过百度、谷歌查找了好半天,最终经历了一番坎坷才解决,具体过程且听我娓娓道来!android

1、windowSoftInputMode

这个是在遇到软键盘相关的问题,脑子里第一个想到的知识点,可是效果如何呢?能解决问题,可是不完美! 先看没有解决的效果图:git

就是说当一个列表的最后一项须要输入时,软键盘会将EditText彻底遮罩! 其实将就一下这个效果也能够,可是咱们能够选择不将就——死磕到底!所以咱们来看看 windowSoftInputMode 怎么解决这个问题?github

Activity获取焦点后,软键盘隐藏与显示
stateUnspecified 不指定软键盘的状态 (隐藏仍是可见) 将由系统选择合适的状态,或依赖主题中的设置,这是对软键盘行为的默认设置
stateUnchanged 保留状态 当 Activity 转至前台时保留软键盘最后所处的任何状态,不管是可见仍是隐藏
stateHidden 隐藏软键盘 当用户确实是向前导航到 Activity,而不是因离开另外一Activity 而返回时隐藏软键盘
stateAlwaysHidden 始终隐藏软键盘 当 Activity 的主窗口有输入焦点时始终隐藏软键盘
stateVisible 显示软键盘 在正常的适宜状况下(当用户向前导航到 Activity 的主窗口时)显示软键盘
stateAlwaysVisible 始终显示软键盘 当用户确实是向前导航到 Activity,而不是因离开另外一Activity 而返回时显示软键盘
在软键盘弹出时,Activity调整策略
adjustUnspecified 主窗口的默认行为,不指定 Activity 的主窗口是否调整尺寸觉得软键盘腾出空间,或者窗口内容是否进行平移以在屏幕上显露当前焦点。 系统会根据窗口的内容是否存在任何可滚动其内容的布局视图来自动选择其中一种模式。 若是存在这样的视图,窗口将进行尺寸调整,前提是可经过滚动在较小区域内看到窗口的全部内容。
adjustResize 始终调整 Activity 主窗口的尺寸来为屏幕上的软键盘腾出空间。当软键盘弹出时,会让布局从新绘制,这种通常适应于带有滑动性质的控制,让其向下滚动,而后适应软键盘的显示。
adjustPan 不调整 Activity 主窗口的尺寸来为软键盘腾出空间, 而是自动平移窗口的内容,使当前焦点永远不被键盘遮盖,让用户始终都能看到其输入的内容。 这一般不如尺寸调整可取,由于用户可能须要关闭软键盘以到达被遮盖的窗口部分或与这些部分进行交互。
adjustNoting 软键盘弹出时,主窗口Activity不会作出任何响应。

上面的表格说明了两个问题:软键盘显示与Activity响应策略。在上面的项目中,软键盘显示是没有问题的,只是Activity的部份内容被遮罩,能够调整策略解决的。那么咱们来依次尝试一下这些个响应策略!api

  • stateUnspecified:

默认的策略一进来软键盘就将底部遮挡了,咱们都没法操做底部的 item ,所以咱们须要进来时不显示软键盘,增长一个策略bash

android:windowSoftInputMode="stateHidden|stateUnspecified"
复制代码

如今进来却是不显示了,可是点击底部的item时仍是同样会被遮挡:微信

  • adjustPan:
android:windowSoftInputMode="stateHidden|stateUnspecified"
复制代码

adjustPan 策略确实将 Activity 主窗口平移上去了,可是个人 Title 部分也平移上去了!这就是我说的不完美的地方,那么咱们试一下主窗口重绘呢?app

  • adjustResize :
android:windowSoftInputMode="stateHidden|adjustResize"
复制代码

adjustResize 策略并无起到做用,底部的输入界面依然被遮罩了,这里我只能接受 adjustPan 策略了!可是还有一个 adjustNoting 策略看看会不会是同样?既然死磕,我们就一个一个都试个遍!ide

  • adjustNoting
android:windowSoftInputMode="stateHidden|adjustNothing"
复制代码

很好,果真没有令咱们失望,确实是不行!布局

而 ConstraintLayout、RelativeLayout 以及 FrameLayout 布局将 EditText 置于布局底部测试默认是正常的。post

可是为何微信聊天页面使用 RecyclerView 布局的效果不是这样的啊?为此我联系到了一个仿朋友圈的大神,他告诉了我第二种方法:动态计算软键盘的高度

2、动态计算软键盘高度

动态计算软键盘的高度这一块,咱们增长一个难度,就是增长软键盘与 EditText 之间的间距,提及来抽象,仍是上图:

至于为何要增长难度,还不是产品要求……既然人家能实现,咱也努把力实现呗!因为动态计算软键盘高度这件事,我们不须要再设置 SoftInputMode 了,由于整个过程纯手工操做,不须要系统其它 api 支持了!

  1. 首先,咱们须要作一些准备工做,将软键盘与主页内容剥离,主页内容就是一个 RecyclerView ,软键盘部分是一个布局包含的 EditText ,软键盘布局如图:

  1. 将上面的软键盘进行封装,这个是重点。提及来比较抽象,就上一张流程图和代码:

public class EmojiPanelView extends LinearLayout implements OnKeyBoardStateListener {
	···
	 public EmojiPanelView(Context context) {
        super(context);
        init();
    }
     private void init() {
        View itemView = LayoutInflater.from(getContext()).inflate(R.layout.view_emoji_panel, this, false);
        mEditText = itemView.findViewById(R.id.edit_text);
        mEditText.setOnTouchListener((v, event) -> {
            showSoftKeyBoard();
            return true;
        });

        mImageSwitch = itemView.findViewById(R.id.img_switch);
        mImageSwitch.setOnClickListener(v -> {
            if (isKeyBoardShow) {
                mImageSwitch.setImageResource(R.drawable.input_keyboard_drawable);
                changeLayoutNullParams(false);
                hideSoftKeyBoard();
                changeEmojiPanelParams(mKeyBoardHeight);
            } else {
                mImageSwitch.setImageResource(R.drawable.input_smile_drawable);
                showSoftKeyBoard();
            }
        });
        ···
        addOnSoftKeyBoardVisibleListener((Activity) getContext(), this);
        addView(itemView);
    }
 @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getY() < Utils.getScreenHeight() - Utils.dp2px(254f) && isShowing()) {
            dismiss();
        }
        return super.onTouchEvent(event);
    }
private void showSoftKeyBoard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null && mEditText != null) {
            mEditText.post(() -> {
                mEditText.requestFocus();
                inputMethodManager.showSoftInput(mEditText, 0);
            });
            new Handler().postDelayed(() -> {
                changeLayoutNullParams(true);
                changeEmojiPanelParams(0);
            }, 200);
        }
    }


    private void hideSoftKeyBoard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null && mEditText != null) {
            inputMethodManager.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
        }
    }
 private void changeLayoutNullParams(boolean isShowSoftKeyBoard) {
        LinearLayout.LayoutParams params = (LayoutParams) mLayoutNull.getLayoutParams();
        if (isShowSoftKeyBoard) {
            params.weight = 1;
            params.height = 0;
            mLayoutNull.setLayoutParams(params);
        } else {
            params.weight = 0;
            params.height = mDisplayHeight;
            mLayoutNull.setLayoutParams(params);
        }
    }

    private void changeEmojiPanelParams(int keyboardHeight) {
        if (mLayoutEmojiPanel != null) {
            LinearLayout.LayoutParams params = (LayoutParams) mLayoutEmojiPanel.getLayoutParams();
            params.height = keyboardHeight;
            mLayoutEmojiPanel.setLayoutParams(params);
        }
    }

    boolean isVisiableForLast = false;

    public void addOnSoftKeyBoardVisibleListener(Activity activity, final OnKeyBoardStateListener listener) {
        final View decorView = activity.getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect rect = new Rect();
            decorView.getWindowVisibleDisplayFrame(rect);
            //计算出可见屏幕的高度
            int displayHight = rect.bottom - rect.top;
            //得到屏幕总体的高度
            int hight = decorView.getHeight();
            //得到键盘高度
            int keyboardHeight = hight - displayHight - Utils.calcStatusBarHeight(getContext());
            boolean visible = (double) displayHight / hight < 0.8;
            if (visible != isVisiableForLast) {
                listener.onSoftKeyBoardState(visible, keyboardHeight, displayHight - Utils.dp2px(48f));
            }
            isVisiableForLast = visible;
        });
    }


    @Override
    public void onSoftKeyBoardState(boolean visible, int keyboardHeight, int displayHeight) {
        this.isKeyBoardShow = visible;
        if (visible) {
            mKeyBoardHeight = keyboardHeight;
            mDisplayHeight = displayHeight;
        }
    }

	}
复制代码
  1. 将自定义的布局加入到主页内容当中,而后咱们不用设置 windowSoftInputMode 就能够了。布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.CustomActivity">

    <include
            android:id="@+id/custom_top_layout"
            layout="@layout/toolbar_layout"/>

    <android.support.v7.widget.RecyclerView
            android:id="@+id/custom_items"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintTop_toBottomOf="@+id/custom_top_layout"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
    >

    </android.support.v7.widget.RecyclerView>

    <com.sasucen.softinput.widget.EmojiPanelView
            android:id="@+id/layout_face_panel"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_constraintBottom_toBottomOf="parent">

    </com.sasucen.softinput.widget.EmojiPanelView>

</android.support.constraint.ConstraintLayout>

复制代码

效果图:

这个效果仍是不错的,可是如今大部分APP都是沉浸式状态栏了,那么咱们也加上沉浸式状态栏看看!

哦豁,输入框被遮罩了!接下来我们进入第三步——最终填坑!

最终填坑


我在走到这个地方的时候,当时记得抓瞎。百度了好多都没有说起说起软键盘遮罩和沉浸式状态栏之间的联系,使用windowSoftInputMode 的时候有效果,可是并不理想,由于EditText与软键盘没有间距了,以下图。

后来咨询上面的大佬的时候,他给了我一个思路——状态栏高度的丢失。后来我尝试在屏幕可见高度以及屏幕总体高度的尺寸上作计算,结果都失败了,EditText 彻底被遮罩!由于无论 layout 增长仍是仍是减小状态栏的高度,EditText 的位置始终在软键盘遮罩的位置。原本打算经过设置 titbar 的 padding 和修改状态栏的颜色,实现沉浸式状态栏,可是钻牛角尖的我始终不甘心!后来想起以前看到的一篇文章随手记技术团队的博客介绍“fitsSystemWindows”属性的说明,因而我进行了尝试:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.CustomActivity">

   ······

    <com.sasucen.softinput.widget.EmojiPanelView
            android:id="@+id/layout_face_panel"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:layout_constraintBottom_toBottomOf="parent">

    </com.sasucen.softinput.widget.EmojiPanelView>

</android.support.constraint.ConstraintLayout>

复制代码


以上所述便是我本身关于软键盘的踩坑总结,但愿本身在下次不清楚的时候能够回来看看,也但愿能够帮助到有须要的人。若有谬误,还请各位指正!

源码

相关文章
相关标签/搜索