热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

Android开发教程之获取系统输入法高度的正确姿势

这篇文章主要给大家介绍了关于Android开发教程之获取系统输入法高度的正确姿势,文中通过示例代码介绍的非常详细,对大家学习或者使用Android具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

问题与解决

在Android应用的开发中,有一些需求需要我们获取到输入法的高度,但是官方的API并没有提供类似的方法,所以我们需要自己来实现。

查阅了网上很多资料,试过以后都不理想。

比如有的方法通过监听布局的变化来计算输入法的高度,这种方式在Activity的配置中配置为"android:windowSoftInputMode="adjustResize""时没有问题,可以正确获取输入法的高度,因为布局此时确实会动态的调整。

但是当Activity配置为"android:windowSoftInputMode="adjustNothing""时,布局不会在输入法弹出时进行调整,上面的方式就会扑街。

不过经过一番探索和测试,终于发现了一种方式可以在即使设置为adjustNothing时也可以正确计算高度放方法。

同时也感谢这位外国朋友:

GitHub地址

方法如下

其实也就两个类,我也做了一些修改,解决了一些问题,这里也贴出来:

KeyboardHeightObserver.java

/**
 * The observer that will be notified when the height of 
 * the keyboard has changed
 */
public interface KeyboardHeightObserver {

 /** 
  * Called when the keyboard height has changed, 0 means keyboard is closed,
  * >= 1 means keyboard is opened.
  * 
  * @param height  The height of the keyboard in pixels
  * @param orientation The orientation either: Configuration.ORIENTATION_PORTRAIT or 
  *      Configuration.ORIENTATION_LANDSCAPE
  */
 void onKeyboardHeightChanged(int height, int orientation);
}

KeyboardHeightProvider.java

/**
 * The keyboard height provider, this class uses a PopupWindow
 * to calculate the window height when the floating keyboard is opened and closed. 
 */
public class KeyboardHeightProvider extends PopupWindow {

 /** The tag for logging purposes */
 private final static String TAG = "sample_KeyboardHeightProvider";

 /** The keyboard height observer */
 private KeyboardHeightObserver observer;

 /** The cached landscape height of the keyboard */
 private int keyboardLandscapeHeight;

 /** The cached portrait height of the keyboard */
 private int keyboardPortraitHeight;

 /** The view that is used to calculate the keyboard height */
 private View popupView;

 /** The parent view */
 private View parentView;

 /** The root activity that uses this KeyboardHeightProvider */
 private Activity activity;

 /** 
  * Construct a new KeyboardHeightProvider
  * 
  * @param activity The parent activity
  */
 public KeyboardHeightProvider(Activity activity) {
  super(activity);
  this.activity = activity;

  LayoutInflater inflator = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
  this.popupView = inflator.inflate(R.layout.keyboard_popup_window, null, false);
  setContentView(popupView);

  setSoftInputMode(LayoutParams.SOFT_INPUT_ADJUST_RESIZE | LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
  setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);

  parentView = activity.findViewById(android.R.id.content);

  setWidth(0);
  setHeight(LayoutParams.MATCH_PARENT);

  popupView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
     if (popupView != null) {
      handleOnGlobalLayout();
     }
    }
   });
 }

 /**
  * Start the KeyboardHeightProvider, this must be called after the onResume of the Activity.
  * PopupWindows are not allowed to be registered before the onResume has finished
  * of the Activity.
  */
 public void start() {

  if (!isShowing() && parentView.getWindowToken() != null) {
   setBackgroundDrawable(new ColorDrawable(0));
   showAtLocation(parentView, Gravity.NO_GRAVITY, 0, 0);
  }
 }

 /**
  * Close the keyboard height provider, 
  * this provider will not be used anymore.
  */
 public void close() {
  this.observer = null;
  dismiss();
 }

 /** 
  * Set the keyboard height observer to this provider. The 
  * observer will be notified when the keyboard height has changed. 
  * For example when the keyboard is opened or closed.
  * 
  * @param observer The observer to be added to this provider.
  */
 public void setKeyboardHeightObserver(KeyboardHeightObserver observer) {
  this.observer = observer;
 }
 
 /**
  * Get the screen orientation
  *
  * @return the screen orientation
  */
 private int getScreenOrientation() {
  return activity.getResources().getConfiguration().orientation;
 }

 /**
  * Popup window itself is as big as the window of the Activity. 
  * The keyboard can then be calculated by extracting the popup view bottom 
  * from the activity window height. 
  */
 private void handleOnGlobalLayout() {

  Point screenSize = new Point();
  activity.getWindowManager().getDefaultDisplay().getSize(screenSize);

  Rect rect = new Rect();
  popupView.getWindowVisibleDisplayFrame(rect);

  // REMIND, you may like to change this using the fullscreen size of the phone
  // and also using the status bar and navigation bar heights of the phone to calculate
  // the keyboard height. But this worked fine on a Nexus.
  int orientation = getScreenOrientation();
  int keyboardHeight = screenSize.y - rect.bottom;
  
  if (keyboardHeight == 0) {
   notifyKeyboardHeightChanged(0, orientation);
  }
  else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
   this.keyboardPortraitHeight = keyboardHeight; 
   notifyKeyboardHeightChanged(keyboardPortraitHeight, orientation);
  } 
  else {
   this.keyboardLandscapeHeight = keyboardHeight; 
   notifyKeyboardHeightChanged(keyboardLandscapeHeight, orientation);
  }
 }

 private void notifyKeyboardHeightChanged(int height, int orientation) {
  if (observer != null) {
   observer.onKeyboardHeightChanged(height, orientation);
  }
 }
}

使用方法

此处以在Activity中的使用进行举例。

实现接口

引入这两个类后,在当前Activity中实现接口KeyboardHeightObserver:

@Override
public void onKeyboardHeightChanged(int height, int orientation) {
 String or = orientation == Configuration.ORIENTATION_PORTRAIT ? "portrait" : "landscape";
 Logger.d(TAG, "onKeyboardHeightChanged in pixels: " + height + " " + or);
}

定义并初始化

在当前Activity定义成员变量,并在onCreate()中进行初始化

private KeyboardHeightProvider mKeyboardHeightProvider;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
 ...
 mKeyboardHeightProvider = new KeyboardHeightProvider(this);
 new Handler().post(() -> mKeyboardHeightProvider.start());
}

生命周期处理

初始化完成后,我们要在Activity中的生命周期中也要进行处理,以免内存泄露。

@Override
protected void onResume() {
 super.onResume();
 mKeyboardHeightProvider.setKeyboardHeightObserver(this);
}

@Override
protected void onPause() {
 super.onPause();
 mKeyboardHeightProvider.setKeyboardHeightObserver(null);
}

@Override
protected void onDestroy() {
 super.onDestroy();
 mKeyboardHeightProvider.close();
}

总结

此时我们就可以正确获取的当前输入法的高度了,即使android:windowSoftInputMode="adjustNothing"时也可以正确获取到,这正是这个方法的强大之处,利用这个方法可以实现比如类似微信聊天的界面,流畅切换输入框,表情框等。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。


推荐阅读
  • 本文内容为asp.net微信公众平台开发的目录汇总,包括数据库设计、多层架构框架搭建和入口实现、微信消息封装及反射赋值、关注事件、用户记录、回复文本消息、图文消息、服务搭建(接入)、自定义菜单等。同时提供了示例代码和相关的后台管理功能。内容涵盖了多个方面,适合综合运用。 ... [详细]
  • Android中高级面试必知必会,积累总结
    本文介绍了Android中高级面试的必知必会内容,并总结了相关经验。文章指出,如今的Android市场对开发人员的要求更高,需要更专业的人才。同时,文章还给出了针对Android岗位的职责和要求,并提供了简历突出的建议。 ... [详细]
  • 【Windows】实现微信双开或多开的方法及步骤详解
    本文介绍了在Windows系统下实现微信双开或多开的方法,通过安装微信电脑版、复制微信程序启动路径、修改文本文件为bat文件等步骤,实现同时登录两个或多个微信的效果。相比于使用虚拟机的方法,本方法更简单易行,适用于任何电脑,并且不会消耗过多系统资源。详细步骤和原理解释请参考本文内容。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • Java学习笔记之使用反射+泛型构建通用DAO
    本文介绍了使用反射和泛型构建通用DAO的方法,通过减少代码冗余度来提高开发效率。通过示例说明了如何使用反射和泛型来实现对不同表的相同操作,从而避免重复编写相似的代码。该方法可以在Java学习中起到较大的帮助作用。 ... [详细]
  • 原理:dismiss再弹出,把dialog设为全局对象。if(dialog!null&&dialog.isShowing()&&!(Activity.)isFinishing()) ... [详细]
  • 2016 linux发行版排行_灵越7590 安装 linux (manjarognome)
    RT之前做了一次灵越7590黑苹果炒作业的文章,希望能够分享给更多不想折腾的人。kawauso:教你如何给灵越7590黑苹果抄作业​zhuanlan.z ... [详细]
  • YOLOv7基于自己的数据集从零构建模型完整训练、推理计算超详细教程
    本文介绍了关于人工智能、神经网络和深度学习的知识点,并提供了YOLOv7基于自己的数据集从零构建模型完整训练、推理计算的详细教程。文章还提到了郑州最低生活保障的话题。对于从事目标检测任务的人来说,YOLO是一个熟悉的模型。文章还提到了yolov4和yolov6的相关内容,以及选择模型的优化思路。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 本文介绍了在Win10上安装WinPythonHadoop的详细步骤,包括安装Python环境、安装JDK8、安装pyspark、安装Hadoop和Spark、设置环境变量、下载winutils.exe等。同时提醒注意Hadoop版本与pyspark版本的一致性,并建议重启电脑以确保安装成功。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 如何在服务器主机上实现文件共享的方法和工具
    本文介绍了在服务器主机上实现文件共享的方法和工具,包括Linux主机和Windows主机的文件传输方式,Web运维和FTP/SFTP客户端运维两种方式,以及使用WinSCP工具将文件上传至Linux云服务器的操作方法。此外,还介绍了在迁移过程中需要安装迁移Agent并输入目的端服务器所在华为云的AK/SK,以及主机迁移服务会收集的源端服务器信息。 ... [详细]
  • SpringBoot整合SpringSecurity+JWT实现单点登录
    SpringBoot整合SpringSecurity+JWT实现单点登录,Go语言社区,Golang程序员人脉社 ... [详细]
author-avatar
暗蓝语依_431
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有