当前位置: 移动技术网 > 移动技术>移动开发>Android > Android开发教程之获取系统输入法高度的正确姿势

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

2019年08月02日  | 移动技术网移动技术  | 我要评论

问题与解决

在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"时也可以正确获取到,这正是这个方法的强大之处,利用这个方法可以实现比如类似微信聊天的界面,流畅切换输入框,表情框等。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网