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

前言

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

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

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

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 尝试控制键盘。若有问题,请留言,谢谢!

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • 为之于未有,治之于未乱。 在以往的项目开发中,关于软键盘的知识点一直比较模糊,只是知道简单的使用,当遇到问题的时候...
    七戈阅读 939评论 0 1
  • 如果在Activity中的布局的下方有EditText,获取焦点弹出软键盘的时候,如果不做处理,软键盘可能会遮挡输...
    张老梦阅读 25,907评论 7 49
  • 关于Adnroid的软键盘 今天在做聊天输入框的时候,发现弹出的软键盘把获得焦点的EditText控件给挡住了,于...
    Sxgg阅读 2,252评论 0 49
  • 软键盘在Android中是重要的输入设备,如果我们对其进行友好化优化的话,对提高用户体验有大大的帮助。 1. In...
    Jinwong阅读 2,205评论 0 8
  • 关于输入框肯定有很多困惑。个人就有困惑来着。。。 主要分几种使用场景: 1. 进入有EditText控件的页面,默...
    MonkeyLei阅读 769评论 0 2