Android开发教程之获取系统输入法高度的正确姿势
问题与解决
在Android应用的开发中,有一些需求需要我们获取到输入法的高度,但是官方的API并没有提供类似的方法,所以我们需要自己来实现。
查阅了网上很多资料,试过以后都不理想。
比如有的方法通过监听布局的变化来计算输入法的高度,这种方式在Activity的配置中配置为"android:windowSoftInputMode="adjustResize""时没有问题,可以正确获取输入法的高度,因为布局此时确实会动态的调整。
但是当Activity配置为"android:windowSoftInputMode="adjustNothing""时,布局不会在输入法弹出时进行调整,上面的方式就会扑街。
不过经过一番探索和测试,终于发现了一种方式可以在即使设置为adjustNothing时也可以正确计算高度放方法。
同时也感谢这位外国朋友:
GitHub地址
方法如下
其实也就两个类,我也做了一些修改,解决了一些问题,这里也贴出来:
KeyboardHeightObserver.java
/** *Theobserverthatwillbenotifiedwhentheheightof *thekeyboardhaschanged */ publicinterfaceKeyboardHeightObserver{ /** *Calledwhenthekeyboardheighthaschanged,0meanskeyboardisclosed, *>=1meanskeyboardisopened. * *@paramheightTheheightofthekeyboardinpixels *@paramorientationTheorientationeither:Configuration.ORIENTATION_PORTRAITor *Configuration.ORIENTATION_LANDSCAPE */ voidonKeyboardHeightChanged(intheight,intorientation); }
KeyboardHeightProvider.java
/** *Thekeyboardheightprovider,thisclassusesaPopupWindow *tocalculatethewindowheightwhenthefloatingkeyboardisopenedandclosed. */ publicclassKeyboardHeightProviderextendsPopupWindow{ /**Thetagforloggingpurposes*/ privatefinalstaticStringTAG="sample_KeyboardHeightProvider"; /**Thekeyboardheightobserver*/ privateKeyboardHeightObserverobserver; /**Thecachedlandscapeheightofthekeyboard*/ privateintkeyboardLandscapeHeight; /**Thecachedportraitheightofthekeyboard*/ privateintkeyboardPortraitHeight; /**Theviewthatisusedtocalculatethekeyboardheight*/ privateViewpopupView; /**Theparentview*/ privateViewparentView; /**TherootactivitythatusesthisKeyboardHeightProvider*/ privateActivityactivity; /** *ConstructanewKeyboardHeightProvider * *@paramactivityTheparentactivity */ publicKeyboardHeightProvider(Activityactivity){ super(activity); this.activity=activity; LayoutInflaterinflator=(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(newOnGlobalLayoutListener(){ @Override publicvoidonGlobalLayout(){ if(popupView!=null){ handleOnGlobalLayout(); } } }); } /** *StarttheKeyboardHeightProvider,thismustbecalledaftertheonResumeoftheActivity. *PopupWindowsarenotallowedtoberegisteredbeforetheonResumehasfinished *oftheActivity. */ publicvoidstart(){ if(!isShowing()&&parentView.getWindowToken()!=null){ setBackgroundDrawable(newColorDrawable(0)); showAtLocation(parentView,Gravity.NO_GRAVITY,0,0); } } /** *Closethekeyboardheightprovider, *thisproviderwillnotbeusedanymore. */ publicvoidclose(){ this.observer=null; dismiss(); } /** *Setthekeyboardheightobservertothisprovider.The *observerwillbenotifiedwhenthekeyboardheighthaschanged. *Forexamplewhenthekeyboardisopenedorclosed. * *@paramobserverTheobservertobeaddedtothisprovider. */ publicvoidsetKeyboardHeightObserver(KeyboardHeightObserverobserver){ this.observer=observer; } /** *Getthescreenorientation * *@returnthescreenorientation */ privateintgetScreenOrientation(){ returnactivity.getResources().getConfiguration().orientation; } /** *PopupwindowitselfisasbigasthewindowoftheActivity. *Thekeyboardcanthenbecalculatedbyextractingthepopupviewbottom *fromtheactivitywindowheight. */ privatevoidhandleOnGlobalLayout(){ PointscreenSize=newPoint(); activity.getWindowManager().getDefaultDisplay().getSize(screenSize); Rectrect=newRect(); popupView.getWindowVisibleDisplayFrame(rect); //REMIND,youmayliketochangethisusingthefullscreensizeofthephone //andalsousingthestatusbarandnavigationbarheightsofthephonetocalculate //thekeyboardheight.ButthisworkedfineonaNexus. intorientation=getScreenOrientation(); intkeyboardHeight=screenSize.y-rect.bottom; if(keyboardHeight==0){ notifyKeyboardHeightChanged(0,orientation); } elseif(orientation==Configuration.ORIENTATION_PORTRAIT){ this.keyboardPortraitHeight=keyboardHeight; notifyKeyboardHeightChanged(keyboardPortraitHeight,orientation); } else{ this.keyboardLandscapeHeight=keyboardHeight; notifyKeyboardHeightChanged(keyboardLandscapeHeight,orientation); } } privatevoidnotifyKeyboardHeightChanged(intheight,intorientation){ if(observer!=null){ observer.onKeyboardHeightChanged(height,orientation); } } }
使用方法
此处以在Activity中的使用进行举例。
实现接口
引入这两个类后,在当前Activity中实现接口KeyboardHeightObserver:
@Override publicvoidonKeyboardHeightChanged(intheight,intorientation){ Stringor=orientation==Configuration.ORIENTATION_PORTRAIT?"portrait":"landscape"; Logger.d(TAG,"onKeyboardHeightChangedinpixels:"+height+""+or); }
定义并初始化
在当前Activity定义成员变量,并在onCreate()中进行初始化
privateKeyboardHeightProvidermKeyboardHeightProvider; @Override protectedvoidonCreate(@NullableBundlesavedInstanceState){ ... mKeyboardHeightProvider=newKeyboardHeightProvider(this); newHandler().post(()->mKeyboardHeightProvider.start()); }
生命周期处理
初始化完成后,我们要在Activity中的生命周期中也要进行处理,以免内存泄露。
@Override protectedvoidonResume(){ super.onResume(); mKeyboardHeightProvider.setKeyboardHeightObserver(this); } @Override protectedvoidonPause(){ super.onPause(); mKeyboardHeightProvider.setKeyboardHeightObserver(null); } @Override protectedvoidonDestroy(){ super.onDestroy(); mKeyboardHeightProvider.close(); }
总结
此时我们就可以正确获取的当前输入法的高度了,即使android:windowSoftInputMode="adjustNothing"时也可以正确获取到,这正是这个方法的强大之处,利用这个方法可以实现比如类似微信聊天的界面,流畅切换输入框,表情框等。
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。