android 键盘相关常见问题有:
1. 限制输入框内字数,超过字数不让输入,并且提示 2. 点击外部区域键盘自动收起 3. 如何获取键盘高度
下面将对上述问题各个击破。
etreply.setfilters(new inputfilter[]{new inputfilter(){ @override public charsequence filter(charsequence source, int start, int end, spanned dest, int dstart, int dend) { if (source.length() + dest.length() > comment_max_num) { crouton.maketext(apputils.getstring(r.string.infodetail_comment_limit),style.alert).show(); } return null; } }, new inputfilter.lengthfilter(comment_max_num)});
如果当前页面是activity那么可以直接重写dispatchtouchevent方法。在action_down事件时,判断点击的坐标是否在输入框坐标的上面,如果是那么调用隐藏键盘的方法。
如果当前页面是fragment,那么fragment中增加一个dispatchtouchevent方法,内部逻辑同上,在fragment所依赖的activity代码中将dispatchtouchevent事件透传给fragment的dispatchtouchevent,如果键盘需要隐藏,fragment的dispatchtouchevent方法需要返回true,表示消费本次所有触摸事件,不再继续传递。
首先需要知道一点,键盘高度不是固定的。用户使用不同的输入法,高度可能不一样;甚至有些输入法,可以直接调节输入法面板的高度。
没有。
系统给我们提供了一个页面布局变化的监听器ongloballayoutlistener,这个监听器可以通知我们布局发生改变,我们可以在此时获取自己的高度,再通过屏幕宽度和状态栏高度等间接计算出键盘的高度。
那么就有一个问题,ongloballayoutlistener接收到变化动作时,一定是键盘弹出或消失么?不一定。
那为什么使用ongloballayoutlistener可以监听键盘的状态?
我们知道每个view的宽高变化都会导致ongloballayoutlistener的触发,但是对当前activity的window对象中的decorview进行监听时,一般来说,decorview的尺寸不会发生变化,发生变化的主要原因就是键盘的收起和展开,这时候加上简单的判断(变化超过某个阈值)就可以获取键盘的高度,以及是否弹起。
有没有使用ongloballayoutlistener监听键盘失效的情景?在一般情况下,我们对activity的phonewindow中decorview的布局变化进行监听,一般来说,变化值超过60dp就可以认为是键盘弹出或收起了。而且在非全屏主题下,
键盘高度 = 屏幕高度 - 状态栏高度 - 主视图高度 - 标题栏高度, 于是我们可以通过下面代码间接计算出键盘高度。
mdecorview = this.getactivity().getwindow().getdecorview(); mgloballayoutlistener = new viewtreeobserver.ongloballayoutlistener() { @override public void ongloballayout() { rect rect = new rect(); mdecorview.getwindowvisibledisplayframe(rect); int displayheight = rect.bottom; if (math.abs(displayheight - molddecorviewheight) > dp60) { molddecorviewheight =displayheight; int rootheight = mroot.getheight(); int statusbarheight = getstatusbarheight(); int screenheight = getscreenheight(); int titlebarheight = gettitlebarheight(); int keyboardheight = screenheight - statusbarheight -rootheight - titlebarheight; log.i("lxc", "keyboardheight ---> " + keyboardheight + " 键盘: " + (keyboardheight > 0 ? "弹出" : "收起")); } } }; mdecorview.getviewtreeobserver().addongloballayoutlistener(mgloballayoutlistener);
如对本文有疑问, 点击进行留言回复!!
网友评论