欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android监听软键盘弹出与隐藏的两种方法

程序员文章站 2024-02-06 19:02:22
需求: 现在有一个需求是点击一行文本框,弹出一个之前隐藏的输入框,输入完成后按返回键或者其他的东西隐藏键盘和输入框,将输入框的内容填充到文本框中。 实现: 拿到这个需...

需求:

现在有一个需求是点击一行文本框,弹出一个之前隐藏的输入框,输入完成后按返回键或者其他的东西隐藏键盘和输入框,将输入框的内容填充到文本框中。

实现:

拿到这个需求的第一反应就是写一个监听来监听键盘的显示和隐藏来控制输入框的显示和隐藏,控制文本框中的内容。
所以我做了如下操作:

  1. 指定android:windowsoftinputmode="adjustresize|statealwayshidden"这个的做法是为了让键盘弹出时改变布局。
  2. 让activity实现layoutchangelistener,监听布局的改变,当布局发生的改变为屏幕的1/3时我们认为是键盘导致的。
@override 
 public void onlayoutchange(view v, int left, int top, int right, 
     int bottom, int oldleft, int oldtop, int oldright, int oldbottom) { 

   //old是改变前的左上右下坐标点值,没有old的是改变后的左上右下坐标点值 

   //现在认为只要控件将activity向上推的高度超过了1/3屏幕高,就认为软键盘弹起 
   if(oldbottom != 0 && bottom != 0 &&(oldbottom - bottom > keyheight)){ 

     toast.maketext(mainactivity.this, "监听到软键盘弹起...", toast.length_short).show(); 

   }else if(oldbottom != 0 && bottom != 0 &&(bottom - oldbottom > keyheight)){ 

     toast.maketext(mainactivity.this, "监听到软件盘关闭...", toast.length_short).show(); 

   } 

 }

问题:

没错,这样确实是能够做到监听软键盘的弹出和隐藏,这一切都是因为之前设置了indowsoftinputmode=adjustresize,但是当全屏模式下是这个属性是无效的,键盘弹出和隐藏并不会触发onlayouchangelistener。

而项目中使用了systembartintmanager之后,activity就变成了全屏模式所以我做了如下操作

//contentlayout是最外层布局
mchildofcontent = contentlayout.getchildat(0);
mchildofcontent.getviewtreeobserver()
.addongloballayoutlistener(new viewtreeobserver.ongloballayoutlistener() {  
   public void ongloballayout() {    
       possiblyresizechildofcontent();  
}});

private void possiblyresizechildofcontent() {  
int usableheightnow = computeusableheight();  
if (usableheightnow != usableheightprevious) {    
   int usableheightsanskeyboard = mchildofcontent.getrootview().getheight();    
   int heightdifference = usableheightsanskeyboard - usableheightnow;    
   if (heightdifference > (usableheightsanskeyboard / 4)) {      
   // 键盘弹出    
   } else {      
   // 键盘收起      
   productinfo.setvisibility(view.gone);      
   productinfoend.settext(productinfo.gettext().tostring());    
}    
   mchildofcontent.requestlayout();    
    usableheightprevious = usableheightnow;  
}
}
private int computeusableheight() {  
 rect r = new rect();  
mchildofcontent.getwindowvisibledisplayframe(r);  
return (r.bottom - r.top);}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。