前言

软键盘系列文章:

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

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

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

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

1、软键盘开启与关闭

为方便起见,这里用键盘代替软键盘来说明。
平时使用最多的无非就是EditText控件,当点击EditText时键盘就会弹出,当点击底部导航栏返回按钮时键盘收起,如下:

既然已经有弹出、收起键盘的例子,那么找找其如何控制键盘的。

键盘弹出

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

#TextView.javapublic 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)) {//获取InputMethodManagerfinal 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即可。

使用工具类弹出、关闭效果如下:

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"><ImageViewandroid: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><EditTextandroid: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时,效果如下:

可以看出,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

布局被顶上去

SOFT_INPUT_ADJUST_PAN

布局被顶上去

SOFT_INPUT_ADJUST_RESIZE

布局没有动

SOFT_INPUT_ADJUST_NOTHING

布局没有动

通过上面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"><ImageViewandroid: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><EditTextandroid: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 模式下,运行后效果如下:

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

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

android:isScrollContainer="true"

其它不做更改,在SOFT_INPUT_ADJUST_UNSPECIFIED 模式下,运行后效果如下:

可以看到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窗口的构成


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

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

#View.javapublic 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;//根Viewfinal View rootView = anyView.getRootView();if (rootView == null)return;navigationHeight = getNavigationBarHeight(anyView.getContext());//anyView为需要调整高度的View,理论上来说可以是任意的Viewthis.anyView = anyView;this.listener = listener;rootView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {@Overridepublic 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 heightboolean 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为需要调整的VieweditText2 = findViewById(R.id.et2);SoftInputUtil softInputUtil = new SoftInputUtil();softInputUtil.attachSoftInput(editText2, new SoftInputUtil.ISoftInputChanged() {@Overridepublic 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"><ImageViewandroid: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><EditTextandroid: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>

最终效果如下:

可以看出,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

Android-软键盘一招搞定(实践篇)相关推荐

  1. Android-软键盘一招搞定(原理篇)

    前言 软键盘系列文章: Android-软键盘一招搞定(实践篇) Android-软键盘一招搞定(原理篇) 上篇文章分析了软键盘弹出.关闭.获取软键盘高度.常用属性展示等.这部分也是网上涉及软键盘文章 ...

  2. android 软件盘未弹出如何获取高度,Android 软键盘的那些坑,一招搞定!

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

  3. android手机做路由器,怎么让手机变成wifi路由器?一招搞定!

    原标题:怎么让手机变成wifi路由器?一招搞定! 当我们的在某些地方的时候需要上网,可电脑没有可用,或是家里的台式电脑没有无线网卡,这样才能让台式通过无线上网呢!等等问题,今天我们就来说说如何把智能手 ...

  4. Android软键盘的全面解析,让你不再怕控件被遮盖

    本文转载自:https://blog.csdn.net/l540675759/article/details/74528641 背景 1.Android软键盘这块从我入职到现在,是一个一直纠缠我的问题 ...

  5. Android 软键盘显示隐藏判断

    Android软键盘始终感觉是个BUG,难缠 用起来不顺手,每次应用版本涉及到相关问题,总是很尴尬 只能静下心好好梳理一下 1. 软键盘显示原理 软键盘的本质是什么?软键盘其实是一个Dialog In ...

  6. 苹果手机小圆点怎么设置?一招搞定!

    案例:苹果手机上的悬浮球怎么设置? [求助!苹果手机小圆点怎么设置出来啊?弄了好久都没搞懂.] 苹果手机小圆点是一个非常实用的功能,它可以帮助您在打字时更快地移动光标,以便更好地编辑文本.但是,很多人 ...

  7. java id3v2 乱码_【图】(更新最终解决办法)解决 奔驰 U盘 音乐信息乱码问题! 一招搞定~...

    多说了,相信各位车主看图秒懂.在网络搜索和尝试各种方法之后,总结了一,原想只列出最后的解决方法,但为了避免有人和我一样突发奇想浪费时间,把其它的一些没用的简单也讲一.(最终解决方案在最后) ...

  8. Android软键盘windowSoftInputMode的使用与原理(原理篇)

    文章目录 前言 一.可见性原理 1.stateUnchanged 2.stateHidden和stateAlwaysHidden 3.stateVisible和stateAlwaysVisible 4 ...

  9. Android软键盘遮挡的四种解决方案

    Android软键盘遮挡的四种解决方案 参考文章: (1)Android软键盘遮挡的四种解决方案 (2)https://www.cnblogs.com/jerehedu/p/4194125.html ...

最新文章

  1. 用Cordova打包Vue-vux项目
  2. 开源的悲哀——袁萌100天变身实录[2]
  3. 15支持哪些数据库版本 tfs_我司虚拟主机支持脚本及数据库版本一览表
  4. 2017年9月9日普级组 买礼物的艰辛
  5. 第一周周日DailyReporting——PM(李忠)
  6. matlab 性能分析方法,DPCM,PSK系统的MATLAB实现及性能分析
  7. kibana报错Request Timeout after 30000ms故障解决
  8. vue props 多类型_一个TypeScript简例,以及Vue支持TS的一些些事儿
  9. Libmicrohttpd简介
  10. Java8 日期时间类
  11. 两种方法在Qt中使用OpenGL库加载stl三维模型
  12. 【对比分析】vipkid和51talk哪个好?说说我的亲身经历!
  13. 观察 | 从0到700万,钉钉只用3年,原因就是快准狠!
  14. 关注两篇gatekeeper的论坛
  15. Linux文件删除但空间不释放问题篇
  16. Fama三因子和Carhat 四因子的介绍和计算
  17. win10安装提示“我们无法创建新的分区”
  18. Ngrok的注册使用
  19. 怎样给自己取个英文名?
  20. 存钱罐小程序_一罐来统治所有人

热门文章

  1. 大咖集结 | 开发者进阶直通车
  2. Go语言中sort.Search()的使用方法(数组中通过值来取索引)
  3. 目莲救母,一个流传千年的故事。_拔剑-浆糊的传说_新浪博客
  4. 安卓 Android 下载网络图片保存到本地
  5. 苹果Mac OS详细介绍
  6. 如何将excel中纵向的转换成横向保证格式不变,
  7. PowerShell脚本传参
  8. 对Python中文分词模块结巴分词算法过程的理解和分析
  9. 50行代码复制多级文件夹--Java //正常人推荐Ctrl+c/v 手动狗头
  10. 如何在WordPress中创建一个人格测验