Android软键盘状态弹出与消失

本文提供了一种有效的方法来监测Android设备上软键盘的状态变化,包括弹出和隐藏,并通过监听屏幕布局变化实现了这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     最近遇到了关于软键盘的问题,需要获取到软键盘的状态,是否在显示 ,记录一下,方便以后查阅。网上常见的判定状态方法

getWindow().getAttributes().softInputMode== WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED  

来判断软键盘是否打开,若相等则为打开。试了之后,发现这个只对手机自带的键盘有作用,对安装的第三方的输入法没有效果。

    还有介绍使用InputMethodManager 来获取键盘状态,代码如下

 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
 boolean isOpen=imm.isActive();//isOpen若返回true,则表示输入法打开
这种并不能实时获取到键盘的状态,对我依然没有效果。

   后来找到的解决方法,监听屏幕的变化,代码如下:

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

/**
 * 
 * 软键盘的监听
 */

public class KeyBoardShowListener {
    private Context ctx;

    public KeyBoardShowListener(Context ctx) {
        this.ctx = ctx;
    }
    OnKeyboardVisibilityListener keyboardListener;

    public OnKeyboardVisibilityListener getKeyboardListener() {
        return keyboardListener;
    }

    public interface OnKeyboardVisibilityListener {


        void onVisibilityChanged(boolean visible);
    }

    public  void setKeyboardListener(final OnKeyboardVisibilityListener listener, Activity activity) {
        final View activityRootView = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);

        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            private boolean wasOpened;

            private final int DefaultKeyboardDP = 100;

            // From @nathanielwolf answer...  Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
            private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

            private final Rect r = new Rect();

            @Override
            public void onGlobalLayout() {
                // Convert the dp to pixels.
                int estimatedKeyboardHeight = (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

                // Conclude whether the keyboard is shown or not.
                activityRootView.getWindowVisibleDisplayFrame(r);
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                boolean isShown = heightDiff >= estimatedKeyboardHeight;

                if (isShown == wasOpened) {
                    Log.e("Keyboard state", "Ignoring global layout change...");
                    return;
                }

                wasOpened = isShown;
                listener.onVisibilityChanged(isShown);
            }
        });
    }
}

用法如下:

//监听软键盘的状态
new KeyBoardShowListener(Activity.this).setKeyboardListener(
        new KeyBoardShowListener.OnKeyboardVisibilityListener() {
            @Override
            public void onVisibilityChanged(boolean visible) {
                if (visible) {
                    //软键盘已弹出
                    
                } else {
                    //软键盘未弹出
                    
                }
            }
        }, Activity.this);


以下是可能会遇到的一些情况:原文链接  http://snowcoal.com/article/641.html

绑定软键盘到EditText

edit.setFocusable(true);
edit.setFocusableInTouchMode(true);
edit.requestFocus();
InputMethodManager inputManager = (InputMethodManager)edit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(edit, 0);

去除软键盘显示

editMsgView.setText("");
editMsgView.clearFocus();
//close InputMethodManager
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editMsgView.getWindowToken(), 0);

始终不弹出软件键盘

EditText edit=(EditText)findViewById(R.id.edit); edit.setInputType(InputType.TYPE_NULL);

也可以:

InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm.isActive()){  //这里可以判断也可以不判断
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0 );
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值