当前位置 : 主页 > 网络编程 > 其它编程 >

android开发分享Android监听键盘状态获取键盘高度的实现方法

来源:互联网 收集:自由互联 发布时间:2023-07-02
前言android暂时还没有提供一个合适的api来获取监听键盘的状态和高度,而我们又经常会有这个需求.最近我的一个项目中,在ugc页面需要在键盘顶部, 前言 android暂时还没有提供一个合适的
前言android暂时还没有提供一个合适的api来获取监听键盘的状态和高度,而我们又经常会有这个需求.最近我的一个项目中,在ugc页面需要在键盘顶部,

前言

android暂时还没有提供一个合适的api来获取/监听键盘的状态和高度 , 而我们又经常会有这个需求.

最近我的一个项目中,在ugc页面需要在键盘顶部,紧贴着键盘显示一个文字提示,当键盘消失时就隐藏. 因此,我需要监听软键盘的打开/关闭 , 以及获取它的高度.

viewtreeobserver

a view tree observer is used to register listeners that can be notified of global changes in the view tree. such global events include, but are not limited to, layout of the whole tree, beginning of the drawing pass, touch mode change…

android框架提供了一个viewtreeobserver类,它是一个view视图树的观察者类。viewtreeobserver类中定义了一系列的公共接口(public interface)。当一个view attach到一个窗口上时就会创建一个viewtreeobserver对象,这样当一个view的视图树发生改变时,就会调用该对象的某个方法,将事件通知给每个注册的监听者。

ongloballayoutlistener是viewtreeobserver中定义的众多接口中的一个,它用来监听一个视图树中全局布局的改变或者视图树中的某个视图的可视状态的改变。当软键盘由隐藏变为显示,或由显示变为隐藏时,都会调用当前布局中所有存在的view中的viewtreeobserver对象的dispatchongloballayout()方法,此方法中会遍历所有已注册的ongloballayoutlistener,执行相应的回调方法,将全局布局改变的消息通知给每个注册的监听者。

view.getviewtreeobserver().addongloballayoutlistener(listener);

getwindowvisibledisplayframe

retrieve the overall visible display size in which the window this view is attached to has been positioned in.

getwindowvisibledisplayframe()会返回窗口的可见区域高度,通过和屏幕高度相减,就可以得到软键盘的高度了。

完整示例代码

package com.cari.cari.promo.diskon.util; import android.content.context; import android.graphics.rect; import android.util.displaymetrics; import android.util.typedvalue; import android.view.view; import android.view.viewtreeobserver; import java.util.linkedlist; import java.util.list; public class softkeyboardstatewatcher implements viewtreeobserver.ongloballayoutlistener { public interface softkeyboardstatelistener { void onsoftkeyboardopened(int keyboardheightinpx); void onsoftkeyboardclosed(); } private final list listeners = new linkedlist(); private final view activityrootview; private int lastsoftkeyboardheightinpx; private boolean issoftkeyboardopened; private context mcontext; //使用时用这个构造方法 public softkeyboardstatewatcher(view activityrootview, context context) { this(activityrootview, false); this.mcOntext= context; } private softkeyboardstatewatcher(view activityrootview) { this(activityrootview, false); } private softkeyboardstatewatcher(view activityrootview, boolean issoftkeyboardopened) { this.activityrootview = activityrootview; this.issoftkeyboardopened = issoftkeyboardopened; activityrootview.getviewtreeobserver().addongloballayoutlistener(this); } @override public void ongloballayout() { final rect r = new rect(); activityrootview.getwindowvisibledisplayframe(r); final int heightdiff = activityrootview.getrootview().getheight() - (r.bottom - r.top); if (!issoftkeyboardopened notifyonsoftkeyboardopened(heightdiff); } else if (issoftkeyboardopened notifyonsoftkeyboardclosed(); } } public void setissoftkeyboardopened(boolean issoftkeyboardopened) { this.issoftkeyboardopened = issoftkeyboardopened; } public boolean issoftkeyboardopened() { return issoftkeyboardopened; } /** * default value is zero {@code 0}. * * @return last saved keyboard height in px */ public int getlastsoftkeyboardheightinpx() { return lastsoftkeyboardheightinpx; } public void addsoftkeyboardstatelistener(softkeyboardstatelistener listener) { listeners.add(listener); } public void removesoftkeyboardstatelistener(softkeyboardstatelistener listener) { listeners.remove(listener); } /** * @param keyboardheightinpx 可能是包含状态栏的高度和底部虚拟按键的高度 */ private void notifyonsoftkeyboardopened(int keyboardheightinpx) { this.lastsoftkeyboardheightinpx = keyboardheightinpx; for (softkeyboardstatelistener listener : listeners) { if (listener != null) { listener.onsoftkeyboardopened(keyboardheightinpx); } } } private void notifyonsoftkeyboardclosed() { for (softkeyboardstatelistener listener : listeners) { if (listener != null) { listener.onsoftkeyboardclosed(); } } } private static float dptopx(context context, float valueindp) { displaymetrics metrics = context.getresources().getdisplaymetrics(); return typedvalue.applydimension(typedvalue.complex_unit_dip, valueindp, metrics); } }

可以看到, 我建了一个自己的一个listener , 通过这个listener实现我们想要的监听 , 然后在这里处理一些逻辑问题.

主要代码还是在ongloballayout中:

首先通过activityrootview.getwindowvisibledisplayframe(r)检索此视图所附加的窗口所在的整个可见显示大小 ,然后减去,已显示的视图的高度 ,(r.bottom – r.top)就是显示的view的下坐标和上坐标,差即为高度.

至此,我们得到了剩余的高度 . 这个高度可能就是键盘高度了, 为什么说可能呢?因为还么有考虑到顶部的状态栏和底部的虚拟导航栏. 当然也可能不是键盘.

然后我们根据这个高度和之前已知的键盘状态来判断是否为键盘. 并回调给监听者.

使用

scrollview scrollview = findviewbyid(r.id.ugc_scrollview); final softkeyboardstatewatcher watcher = new softkeyboardstatewatcher(scrollview, this); watcher.addsoftkeyboardstatelistener( new softkeyboardstatewatcher.softkeyboardstatelistener() { @override public void onsoftkeyboardopened(int keyboardheightinpx) { constraintlayout.layoutparams layoutparamsvideo = (constraintlayout.layoutparams) merror1000tv.getlayoutparams(); layoutparamsvideo.setmargins(0, 0, 0, keyboardheightinpx - screenutils.getstatusheight(ugceditactivity.this) - screenutils.getbottomstatusheight(ugceditactivity.this)); } @override public void onsoftkeyboardclosed() { merror1000tv.setvisibility(view.gone); } } );

scrollview是整个页面的根布局, 我通过监听它来实现对整个布局的监听.

merror1000tv就是我一开始提到的要紧贴键盘顶部显示的一个textview了.

我通过layoutparams给它设置边距 , 只设置了底部边距 , 值为返回的”键盘高度”- 顶部状态栏高度-虚拟导航栏的高度. 得到真实的键盘高度.

在onsoftkeyboardopened和onsoftkeyboardclosed这两个回调中, 处理自己的逻辑就好了.

然后放上我这边屏幕工具类screenutils的代码, 需要的可以复制下来

screenutils

package com.cari.promo.diskon.util; import android.app.activity; import android.content.context; import android.graphics.bitmap; import android.graphics.rect; import android.util.displaymetrics; import android.view.display; import android.view.view; import android.view.windowmanager; import java.lang.reflect.method; public class screenutils { private screenutils() { /* cannot be instantiated */ throw new unsupportedoperationexception("cannot be instantiated"); } /** * 获得屏幕高度 * * @param context * @return */ public static int getscreenwidth(context context) { windowmanager wm = (windowmanager) context .getsystemservice(context.window_service); displaymetrics outmetrics = new displaymetrics(); wm.getdefaultdisplay().getmetrics(outmetrics); return outmetrics.widthpixels; } /** * 获得屏幕宽度 * * @param context * @return */ public static int getscreenheight(context context) { windowmanager wm = (windowmanager) context .getsystemservice(context.window_service); displaymetrics outmetrics = new displaymetrics(); wm.getdefaultdisplay().getmetrics(outmetrics); return outmetrics.heightpixels; } /** * 获得状态栏的高度 * * @param context * @return */ public static int getstatusheight(context context) { int statusheight = -1; try { class clazz = class.forname("com.android.internal.r$dimen"); object object = clazz.newinstance(); int height = integer.parseint(clazz.getfield("status_bar_height") .get(object).tostring()); statusheight = context.getresources().getdimensionpixelsize(height); } catch (exception e) { e.printstacktrace(); } return statusheight; } /** * 获取当前屏幕截图,包含状态栏 * * @param activity * @return */ public static bitmap snapshotwithstatusbar(activity activity) { view view = activity.getwindow().getdecorview(); view.setdrawingcacheenabled(true); view.builddrawingcache(); bitmap bmp = view.getdrawingcache(); int width = getscreenwidth(activity); int height = getscreenheight(activity); bitmap bp = null; bp = bitmap.createbitmap(bmp, 0, 0, width, height); view.destroydrawingcache(); return bp; } /** * 获取当前屏幕截图,不包含状态栏 * * @param activity * @return */ public static bitmap snapshotwithoutstatusbar(activity activity) { view view = activity.getwindow().getdecorview(); view.setdrawingcacheenabled(true); view.builddrawingcache(); bitmap bmp = view.getdrawingcache(); rect frame = new rect(); activity.getwindow().getdecorview().getwindowvisibledisplayframe(frame); int statusbarheight = frame.top; int width = getscreenwidth(activity); int height = getscreenheight(activity); bitmap bp = null; bp = bitmap.createbitmap(bmp, 0, statusbarheight, width, height - statusbarheight); view.destroydrawingcache(); return bp; } /** * 获取 虚拟按键的高度 * * @param context 上下文 * @return 虚拟键高度 */ public static int getbottomstatusheight(context context) { int totalheight = getabsoluteheight(context); int cOntentheight= getscreenheight(context); return totalheight - contentheight; } /** * 获取屏幕原始尺寸高度,包括虚拟功能键高度 * * @param context 上下文 * @return the absolute height of the available display size in pixels. */ private static int getabsoluteheight(context context) { int absoluteheight = 0; windowmanager windowmanager = (windowmanager) context.getsystemservice(context.window_service); display display = null; if (windowmanager != null) { display = windowmanager.getdefaultdisplay(); } displaymetrics displaymetrics = new displaymetrics(); @suppresswarnings("rawtypes") class c; try { c = class.forname("android.view.display"); @suppresswarnings("unchecked") method method = c.getmethod("getrealmetrics", displaymetrics.class); method.invoke(display, displaymetrics); absoluteheight = displaymetrics.heightpixels; } catch (exception e) { e.printstacktrace(); } return absoluteheight; } }

全文完.

总结

【感谢龙石为本站提供数据采集系统 http://www.longshidata.com/pages/government.html 】
上一篇:Python验证码识别处理实例
下一篇:没有了
网友评论