Android-软键盘一招搞定(实践篇)

前言

软键盘系列文章:

Android-软键盘一招搞定(实践篇)
Android-软键盘一招搞定(原理篇)

软键盘是Android进行用户交互的重要途径之一,Android应用开发基本无法避免不使用它。然而官方没有提供一套明确的API来获取诸如:软键盘是否正在展示、软键盘高度等。本篇将着眼如此,探索解决方案。

通过本篇文章,你将了解到:

1、软键盘开启与关闭
2、软键盘界面适配
3、软键盘高度获取

1、软键盘开启与关闭

为方便起见,这里用键盘代替软键盘来说明。
平时使用最多的无非就是EditText控件,当点击EditText时键盘就会弹出,当点击底部导航栏返回按钮时键盘收起,如下:
device-2020-10-11-102755 (2).gif
既然已经有弹出、收起键盘的例子,那么找找其如何控制键盘的。

键盘弹出

先看看看看EditText如何弹出键盘的。

#TextView.java
    public boolean onTouchEvent(MotionEvent event) {
        final int action = event.getActionMasked();
        ...
        final boolean touchIsFinished = (action == MotionEvent.ACTION_UP)
                && (mEditor == null || !mEditor.mIgnoreActionUpEvent) && isFocused();
        if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()
                && mText instanceof Spannable && mLayout != null) {
            boolean handled = false;
            ...
            if (touchIsFinished && (isTextEditable() || textIsSelectable)) {
                //获取InputMethodManager
                final InputMethodManager imm = getInputMethodManager();
                viewClicked(imm);
                if (isTextEditable() && mEditor.mShowSoftInputOnFocus && imm != null) {
                    //弹出键盘
                    imm.showSoftInput(this, 0);
                }
                ...
            }
            ...
        }
        return superResult;
    }

可以看出弹出键盘只需要两个步骤:

1、获取InputMethodManager 实例
2、调用showSoftInput(xx)

键盘关闭

         InputMethodManager inputMethodManager = (InputMethodManager)view.getContext().getSystemService(INPUT_METHOD_SERVICE);
         inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);

同样的,可以看出收起键盘只需要两步:

1、获取InputMethodManager 实例
2、调用hideSoftInputFromWindow(xx)

弹出/关闭 工具类

将弹出/关闭方法提取出来:

public class SoftInputUtil {
    public static void showSoftInput(View view) {
        if (view == null)
            return;
        InputMethodManager inputMethodManager = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.showSoftInput(view, 0);
        }
    }

    public static void hideSoftInput(View view) {
        if (view == null)
            return;
        InputMethodManager inputMethodManager = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

有几点需要注意的是:

1、inputMethodManager.showSoftInput(xx) 一般来说需要传入的View是EditText 类型的。如果传入其它View,需要进行额外的操作才能弹出键盘。
2、inputMethodManager.showSoftInput(xx) 、inputMethodManager. hideSoftInputFromWindow(xx) 两个方法的最后一个参数用来匹配关闭键盘时判断当初弹出键盘时传入的类型,一般填0即可。
3、inputMethodManager. hideSoftInputFromWindow(xx) 第一个参数传入的IBinder windowToken类型。每个Activity创建时候会生成windowToken,该值存储在AttachInfo里,因此对于同一个Activity里的ViewTree,每个View持有的windowToken 都是指向通过一个对象。

针对上述1、3点再补充一下:
对于1点:

假设当传入的View是Button类型时,需要设置Button.setFocusableInTouchMode(true),此时能够弹出键盘。
比较完善的做法是:还需要在onTouchEvent(xx)里弹出键盘、需要将Button与键盘关联。实际上就是模仿EditText的工作,系统都提供了EditText接收输入字符,没必要自己再整一套,因此弹出键盘时通常传入EditText。

对于3点:

因为同一个ViewTree里的windowToken都是一致的,因此不一定要传入EditText,可以传入Button等,只要属于同一个ViewTree即可。

使用工具类弹出、关闭效果如下:
device-2020-10-11-212952 (1).gif

2、软键盘界面适配

一个小Demo

先看看Demo,设置Activity布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myviewgroup"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="20dp"
    android:orientation="vertical"
    android:layout_gravity="center_vertical"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/iv"
        android:src="@drawable/test"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_width="match_parent"
        android:layout_height="300dp">
    </ImageView>

    <EditText
        android:hint="输入框2"
        android:id="@+id/et2"
        android:layout_gravity="bottom"
        android:layout_marginTop="200dp"
        android:layout_width="100dp"
        android:layout_height="40dp">
    </EditText>
    
</LinearLayout>

很简单,就是个ImageView和EditText在LinearLayout里纵向排列。
当点击EditText时,效果如下:
default.gif
可以看出,EditText随着键盘顶上去了,ImageView随着键盘顶上去了。
试想以下问题如何解决。

1、当键盘弹出时,只想EditText顶上去,ImageView保持不动
2、当键盘弹出时,任何View都不需要顶上去

先简单分析:
我们知道软键盘其实就是个Dialog,当键盘弹起的时,实际上当前能看到的是两个Window:1是Activity的Window,2是Dialog的Window。问题的关键是Dialog的Window展示遮盖了Activity的Window的部分区域,为了使EditText能够被看到,Activity的布局被向上顶上去,猜想Window 属性有控制是否顶上去的参数。还真有,这个参数就是WindowManager.LayoutParams.softInputMode。

WindowManager.LayoutParams.softInputMode

softInputMode 顾名思义:软键盘的模式
它控制着键盘是否可见、键盘关联的EditText是否跟随键盘移动等,我们重点关注以下属性:

#WindowManager.java
public static final int SOFT_INPUT_ADJUST_UNSPECIFIED = 0x00;
public static final int SOFT_INPUT_ADJUST_RESIZE = 0x10;
public static final int SOFT_INPUT_ADJUST_PAN = 0x20;
public static final int SOFT_INPUT_ADJUST_NOTHING = 0x30;

分别介绍以上取值的作用:

SOFT_INPUT_ADJUST_UNSPECIFIED
不指定调整方式,系统自行决定使用哪种调整方式

SOFT_INPUT_ADJUST_RESIZE
调整方式为布局需要重新计算大小适配当前可见区域

SOFT_INPUT_ADJUST_PAN
调整方式为布局需要整体移动

SOFT_INPUT_ADJUST_NOTHING
不做任何操作

设置softInputMode有两种方式:
1、代码设置:
获取Window对象并设置

getWindow().getAttributes().softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN;

2、xml里设置
在AndroidManifest.xml设置Activity 属性

android:windowSoftInputMode="adjustResize"

来看看各种取值的效果:
SOFT_INPUT_ADJUST_UNSPECIFIED
default.gif
布局被顶上去

SOFT_INPUT_ADJUST_PAN
default.gif
布局被顶上去

SOFT_INPUT_ADJUST_RESIZE
device-2020-10-14-211817.gif
布局没有动

SOFT_INPUT_ADJUST_NOTHING
device-2020-10-14-211817.gif
布局没有动

通过上面4张图,你可能就有疑惑了:怎么SOFT_INPUT_ADJUST_UNSPECIFIED和SOFT_INPUT_ADJUST_PAN 效果一致,SOFT_INPUT_ADJUST_RESIZE和SOFT_INPUT_ADJUST_NOTHING效果一致呢?
SOFT_INPUT_ADJUST_PAN 效果是顶上去,SOFT_INPUT_ADJUST_NOTHING 是不做任何操作。
这两个值得效果没有疑义,关键是SOFT_INPUT_ADJUST_RESIZE和SOFT_INPUT_ADJUST_UNSPECIFIED效果。

先来分析SOFT_INPUT_ADJUST_RESIZE
将Activity布局文件改造如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myviewgroup"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="20dp"
    android:orientation="vertical"
    android:layout_gravity="center_vertical"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/iv"
        android:src="@drawable/test"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:scaleType="fitXY"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="0dp">
    </ImageView>

    <EditText
        android:hint="输入框2"
        android:id="@+id/et2"
        android:layout_gravity="bottom"
        android:layout_marginTop="10dp"
        android:layout_width="100dp"
        android:layout_height="40dp">
    </EditText>
    
</LinearLayout>

实际上以上布局仅仅是扩大了ImageView展示范围。
关于ImageView scaleType 请移步:ImageView scaleType 各种不同效果解析
其它不做更改,在SOFT_INPUT_ADJUST_RESIZE 模式下,运行后效果如下:
device-2020-10-14-213218.gif

可以看出,ImageView被压缩了,说明布局文件重新计算大小了。
改变布局前后的效果为什么不同?这个答案在下篇"原理篇"揭晓。

再先来分析SOFT_INPUT_ADJUST_UNSPECIFIED
还是将Activity布局文件改变,在ImageView里增加isScrollContainer 属性

android:isScrollContainer="true"

其它不做更改,在SOFT_INPUT_ADJUST_UNSPECIFIED 模式下,运行后效果如下:
device-2020-10-14-213218.gif

可以看到SOFT_INPUT_ADJUST_UNSPECIFIED 模式下产生的效果可能与SOFT_INPUT_ADJUST_PAN相同,也可能与SOFT_INPUT_ADJUST_RESIZE相同,也就是:

当SOFT_INPUT_ADJUST_UNSPECIFIED 模式时,实际上是选择了SOFT_INPUT_ADJUST_RESIZE或者SOFT_INPUT_ADJUST_PAN 模式进行展示。

通过对以上四种取值的实验,再来看看之前Demo里提出的两个问题:

1、当键盘弹出时,只想EditText顶上去,ImageView保持不动
答:接下来分析
2、当键盘弹出时,任何View都不需要顶上去
答:设置SOFT_INPUT_ADJUST_NOTHING

3、软键盘高度获取

对于上面的问题1,既然想要EditText单独顶上去,那么就需要知道当前键盘弹出的高度,再设置EditText坐标即可。
问题的关键转变为如何获取键盘的高度。

Activity窗口的构成

image.png
通常来说,手机由状态栏、内容区域、导航栏组成。
一般情况下(除去导航栏隐藏,状态栏沉浸)对于我们来说,写的布局文件都会展示在内容区域,这部分是"能看到的"。
当键盘弹出的时候,会遮盖部分内容区域:
image.png

因此,需要将被遮住的部分往上移动,移动多少呢?
通过调用方法:

#View.java
    public void getWindowVisibleDisplayFrame(Rect outRect) {
        ...
    }

可见区域的位置记录在outRect里,而整个屏幕高度是已知的,因此就可以计算出被遮挡的区域需要顶上去的偏移量。

一个通用的计算方式

根据上面的分析,将计算方法封装一下:

public class SoftInputUtil {

    private int softInputHeight = 0;
    private boolean softInputHeightChanged = false;

    private boolean isNavigationBarShow = false;
    private int navigationHeight = 0;

    private View anyView;
    private ISoftInputChanged listener;
    private boolean isSoftInputShowing = false;

    public interface ISoftInputChanged {
        void onChanged(boolean isSoftInputShow, int softInputHeight, int viewOffset);
    }

    public void attachSoftInput(final View anyView, final ISoftInputChanged listener) {
        if (anyView == null || listener == null)
            return;

        //根View
        final View rootView = anyView.getRootView();
        if (rootView == null)
            return;

        navigationHeight = getNavigationBarHeight(anyView.getContext());

        //anyView为需要调整高度的View,理论上来说可以是任意的View
        this.anyView = anyView;
        this.listener = listener;

        rootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                //对于Activity来说,该高度即为屏幕高度
                int rootHeight = rootView.getHeight();
                Rect rect = new Rect();
                //获取当前可见部分,默认可见部分是除了状态栏和导航栏剩下的部分
                rootView.getWindowVisibleDisplayFrame(rect);
                
                if (rootHeight - rect.bottom == navigationHeight) {
                    //如果可见部分底部与屏幕底部刚好相差导航栏的高度,则认为有导航栏
                    isNavigationBarShow = true;
                } else if (rootHeight - rect.bottom == 0) {
                    //如果可见部分底部与屏幕底部平齐,说明没有导航栏
                    isNavigationBarShow = false;
                }

                //cal softInput height
                boolean isSoftInputShow = false;
                int softInputHeight = 0;
                //如果有导航栏,则要去除导航栏的高度
                int mutableHeight = isNavigationBarShow == true ? navigationHeight : 0;
                if (rootHeight - mutableHeight > rect.bottom) {
                    //除去导航栏高度后,可见区域仍然小于屏幕高度,则说明键盘弹起了
                    isSoftInputShow = true;
                    //键盘高度
                    softInputHeight = rootHeight - mutableHeight - rect.bottom;
                    if (SoftInputUtils.this.softInputHeight != softInputHeight) {
                        softInputHeightChanged = true;
                        SoftInputUtils.this.softInputHeight = softInputHeight;
                    } else {
                        softInputHeightChanged = false;
                    }
                }

                //获取目标View的位置坐标
                int[] location = new int[2];
                anyView.getLocationOnScreen(location);

                //条件1减少不必要的回调,只关心前后发生变化的
                //条件2针对软键盘切换手写、拼音键等键盘高度发生变化
                if (isSoftInputShowing != isSoftInputShow || (isSoftInputShow && softInputHeightChanged)) {
                    if (listener != null) {
                        //第三个参数为该View需要调整的偏移量
                        //此处的坐标都是相对屏幕左上角(0,0)为基准的
                        listener.onChanged(isSoftInputShow, softInputHeight, location[1] + anyView.getHeight() - rect.bottom);
                    }

                    isSoftInputShowing = isSoftInputShow;
                }
            }
        });
    }


    //***************STATIC METHOD******************

    public static int getNavigationBarHeight(Context context) {
        if (context == null)
            return 0;
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    public static void showSoftInput(View view) {
        if (view == null)
            return;
        InputMethodManager inputMethodManager = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.showSoftInput(view, 0);
        }
    }

    public static void hideSoftInput(View view) {
        if (view == null)
            return;
        InputMethodManager inputMethodManager = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}

使用方式如下:
在Activity里加如下代码:

    private void attachView() {
        
        //editText2为需要调整的View
        editText2 = findViewById(R.id.et2);
        SoftInputUtil softInputUtil = new SoftInputUtil();
        softInputUtil.attachSoftInput(editText2, new SoftInputUtil.ISoftInputChanged() {
            @Override
            public void onChanged(boolean isSoftInputShow, int softInputHeight, int viewOffset) {
                if (isSoftInputShow) {
                    editText2.setTranslationY(et2.getTranslationY() - viewOffset);
                } else {
                    editText2.setTranslationY(0);
                }
            }
        });
    }

并且将windowSoftInputMode 设置为SOFT_INPUT_ADJUST_RESIZE。

android:windowSoftInputMode="adjustResize|stateAlwaysHidden"

stateAlwaysHidden 为默认不显示键盘。

再来看Activity的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myviewgroup"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center_vertical"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/iv"
        android:src="@drawable/test"
        android:background="@color/colorGreen"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_width="match_parent"
        android:layout_height="300dp">
    </ImageView>

    <EditText
        android:hint="输入框2"
        android:id="@+id/et2"
        android:layout_marginTop="100dp"
        android:background="@drawable/bg"
        android:layout_gravity="bottom"
        android:layout_marginHorizontal="10dp"
        android:layout_width="match_parent"
        android:layout_height="40dp">
    </EditText>
</LinearLayout>

最终效果如下:
device-2020-10-16-001523.gif

可以看出,EditText被顶上去了,其它布局没有变化。在动态切换导航栏是否展示之间EeditText也能正常显示。
这就回答了上面的问题1:当键盘弹出时,只想EditText顶上去,ImageView保持不动。
当然对于问题1的还有其它更简单的解决方式,在下一篇会分析。

以上是关于软键盘弹出、关闭、是否展示、软键盘高度、软键盘模式等效果的解析。
你可能还有如下疑惑:

SOFT_INPUT_ADJUST_PAN 为什么能够将布局顶上去?
SOFT_INPUT_ADJUST_RESIZE 为什么能够重新设置布局区域?
SOFT_INPUT_ADJUST_UNSPECIFIED 内部逻辑如何判断?
键盘弹起为什么会执行onLayout?

由于篇幅所限,这些问题将在下篇:Android 软键盘一招搞定(原理篇)分析。

本文基于 Android 10.0。

如果您有需求,请直接拷贝文章里的SoftInputUtil.java 尝试控制键盘。若有问题,请留言,谢谢!

如果您喜欢,请点赞,您的鼓励是我前进的动力。

持续更新中,和我一起步步为营系统、深入学习Android/Java

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值