安卓开发:监听软键盘的显示与隐藏,并作出其他操作

对于安卓的软键盘的显示隐藏,查了好多资料,得出一个结论,就是Google并没有提供接口来直接判断键盘是否是显示状态。
刚好项目中遇到这个问题,目前解决了,就贡献出来给Androider。
我的思路是通过重写父布局来监听布局变化,然后判断可视区域来判定软件盘是否是显示状态

废话不多说,直接上代码,代码中解释,没几行,目前测试没问题

通过重写布局的
onMeasure方法来确定当前布局是否有变化。有变化的话去判断可视区域,继而得出软键盘当前是否是显示状态
代码如下:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if ((isKeyboardShown(this))) {
        //在这做你要做的操作
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

下面这个方法是用来判断当前键盘是否显示

private boolean isKeyboardShown(View rootView) {
    //自己确定键盘的高度,自己可修改
    final int softKeyboardHeight = 100;
    Rect r = new Rect();
    rootView.getWindowVisibleDisplayFrame(r);
    DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
    int heightDiff = rootView.getBottom() - r.bottom;
    return heightDiff > softKeyboardHeight * dm.density;
}

好了,代码就这么多,下面贴上完整代码

/**
 * Created by onlykk on 2016/9/5.
 */
public class IgoneKeybordFrameLayout extends FrameLayout {

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

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

    public IgoneKeybordFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (isKeyboardShown(this)) {

        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    private boolean isKeyboardShown(View rootView) {
        final int softKeyboardHeight = 100;
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
        int heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > softKeyboardHeight * dm.density;
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值