温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-27 08:01:35 来源:脚本之家 阅读:413 作者:JJoom 栏目:移动开发

需求:

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

实现:

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

  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);}

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI