android 键盘弹起/收起监听


Android soft (virtual) keyboard listener
If you use Evernote android app you might have noticed, that when, on a login screen, soft keyboard gets shown (to type password or username) the layout doesn't just scale, or scrolls. It changes (for example Evernotes logo is hidden).

Unfortunately, android api doesn't provide you with the specific tools to listen for a moment, when soft keyboard gets shown, or hidden. But there is a way (dirty hack) to assume that the keyboards state was changed.
We can guess it by listening measure changes in layout.
To do it, first, we need to make our layout to resize and scale instaed of scroll.   Add  android:windowSoftInputMode="adjustResize"  parameter to your activity in manifest.xml. This way, when soft keyboard is called, content will be resized instead of scrolled.

Next step is to actually listen for this resizing. And again, there is a catch. There is no such thing as OnMeasureChangedListener , so the only way is to extend the container layout and do it inside. As an example I extended LinearLayout, and this is what I've got:

public class MyLayout extends LinearLayout {

  public MyLayout(final Context context, final AttributeSet attrs) {
    super(context, attrs);
  }

  public MyLayout(Context context) {
    super(context);
  }

  private OnSoftKeyboardListener onSoftKeyboardListener;

  @Override
  protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
    if (onSoftKeyboardListener != null) {
      final int newSpec = MeasureSpec.getSize(heightMeasureSpec); 
      final int oldSpec = getMeasuredHeight();
      // If layout became smaller, that means something forced it to resize. Probably soft keyboard :)
      if (oldSpec > newSpec){
        onSoftKeyboardListener.onShown();
      } else {
        onSoftKeyboardListener.onHidden();
      }
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }

  public final void setOnSoftKeyboardListener(final OnSoftKeyboardListener listener) {
    this.onSoftKeyboardListener = listener;
  }

  // Simplest possible listener :)
  public interface OnSoftKeyboardListener {
    public void onShown();
    public void onHidden();
  }
}





  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值