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

 更新时间:2018年10月21日 15:32:56   作者:ExampleCode  
这篇文章主要给大家介绍了关于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"时也可以正确获取到,这正是这个方法的强大之处,利用这个方法可以实现比如类似微信聊天的界面,流畅切换输入框,表情框等。

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

相关文章

  • Android端TCP长连接的性能优化教程分享

    Android端TCP长连接的性能优化教程分享

    在开发过程中,我们经常会用到TCP/IP连接实现即时数据传输,下面这篇文章主要给大家介绍了关于Android端TCP长连接的性能优化的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
    2018-03-03
  • Android 自定义手势--输入法手势技术

    Android 自定义手势--输入法手势技术

    这篇文章主要介绍了Android 自定义手势--输入法手势技术的相关资料,需要的朋友可以参考下
    2016-10-10
  • flutter 屏幕尺寸适配和字体大小适配的实现

    flutter 屏幕尺寸适配和字体大小适配的实现

    这篇文章主要介绍了flutter 屏幕尺寸适配和字体大小适配的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • Android使用OKhttp3实现登录注册功能+springboot搭建后端的详细过程

    Android使用OKhttp3实现登录注册功能+springboot搭建后端的详细过程

    这篇教程主要实现Android使用OKhttp3实现登录注册的功能,后端使用SSM框架,本文通过实例图文相结合给大家介绍的非常详细,需要的朋友参考下吧
    2021-07-07
  • Android ConstraintLayout约束布局使用实例介绍

    Android ConstraintLayout约束布局使用实例介绍

    ConstraintLayout是Google在Google I/O 2016大会上发布的一种新的布局容器(ViewGroup),它支持以灵活的方式来放置子控件和调整子控件的大小,下面这篇文章主要给大家介绍了关于Android中ConstraintLayout约束布局详细解析的相关资料,需要的朋友可以参考下
    2022-10-10
  • Android实现简洁的APP更新dialog数字进度条

    Android实现简洁的APP更新dialog数字进度条

    这篇文章主要为大家详细介绍了Android实现简洁的APP更新dialog数字进度条,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04
  • Android ListView 实现上拉加载的示例代码

    Android ListView 实现上拉加载的示例代码

    这篇文章主要介绍了Android ListView 实现上拉加载的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • Android编程滑动效果之Gallery仿图像集浏览实现方法

    Android编程滑动效果之Gallery仿图像集浏览实现方法

    这篇文章主要介绍了Android编程滑动效果之Gallery仿图像集浏览实现方法,结合实例形式详细分析了Gallery浏览图片的原理、步骤与相关实现技巧,需要的朋友可以参考下
    2016-02-02
  • Android中修改TabLayout底部导航条Indicator长短的方法

    Android中修改TabLayout底部导航条Indicator长短的方法

    Tablayout在我们日常开发中经常会遇到,下面这篇文章主要给大家介绍了在Android中修改TabLayout底部导航条Indicator长短的方法,文中给出了详细的示例代码供大家参考学习,需要的朋友们下面来一起看看吧。
    2017-06-06
  • Android仿微信主界面的实现方法

    Android仿微信主界面的实现方法

    这篇文章主要为大家详细介绍了Android仿微信主界面的实现方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04

最新评论