Android如何监听系统输入法弹出显示事件
来源:互联网 发布:淘宝店名的重要性 编辑:程序博客网 时间:2024/05/17 23:08
在Android开发中,我们有些时候需要监听输入法的弹出事件,并做一些自定义的处理。然而,我们并不能通过Android提供的API去实现这个功能,因为Android原生API并没有提供输入法弹出事件的监听器。
根据文档,我们很容易知道Android中输入法的核心就是一个名称为InputMethodService的Service,它在android.inputmethodservice下。通过InputMethodService可以对输入等做一些处理,但是如果需要监听到弹出之后还需要在Activity中做一些处理就很麻烦了。
因此,从另一个角度思考。从输入法弹出会使Activity的布局变化这一性质可以想到,我们可以通过监听Activity布局的高度变化来间接监听输入法的弹出事件。以下是整个实现过程:
1、给Activity的全局布局控件命名为activityRoot:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/activityRoot" >
2、查看Android的API可以得知OnGlobalLayoutListener是一个global layout状态改变的回调函数:
public static interface ViewTreeObserver.OnGlobalLayoutListener:
Interface definition for a callback to be invoked when the global layout state or the visibility of views within the view tree changes.
3、给Activity的global layout设置OnGlobalLayoutListener并判断高度变化大小来判断输入法的弹出:
//监听global layout的大小变化final View activityRootView = findViewById(R.id.activityRoot);activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight(); if (heightDiff > 100) { //高度变小100像素则认为键盘弹出 //这里执行需要的处理 } }});
注意:Activity的属性设置为可调整大小android:windowSoftInputMode="adjustResize",否则输入弹出,Activity的global layout没有变化,这种方法就无效了。
0 0
- Android如何监听系统输入法弹出显示事件
- Android监听系统输入法键盘弹出显示与隐藏事件
- Android 如何监听输入法关闭事件
- [经典技巧]android 如何监听输入法是否弹出或隐藏,监听手机是否是全屏切换
- 如何实现监听Android输入法弹出收回,为什么要使用接口
- Android如何监听:软键盘显示时:返回键事件
- Android如何监听:软键盘显示时:返回键事件
- android 输入法显示和隐藏监听
- android 输入法显示和隐藏监听
- android如何调用显示和隐藏系统默认的输入法
- android如何调用显示和隐藏系统默认的输入法
- android如何调用显示和隐藏系统默认的输入法
- android如何调用显示和隐藏系统默认的输入法
- android如何调用显示和隐藏系统默认的输入法
- android如何调用显示和隐藏系统默认的输入法
- android如何调用显示和隐藏系统默认的输入法
- android如何调用显示和隐藏系统默认的输入法
- android如何调用显示和隐藏系统默认的输入法
- POJ 1111 Image Perimeters
- Stm32定时器中断使LED灯闪烁
- 增加product项目
- 链表知识点(十二)【逆序打印单链表】
- 数据库mysql和oracel在应用中的分页实现
- Android如何监听系统输入法弹出显示事件
- 对协方差矩阵的理解
- SQL 去除重复值进行统计问题
- hdoj 2066 一个人的旅行 【dijstra】
- openfire上——开发环境搭建
- Express 3.0新手指南入门教程
- java.io-接口学习
- Maximum Subarray-最大连续子数组和
- sqlserver xml 传入对象参数