Android监听软键盘的隐藏与显示

转载自:https://blog.csdn.net/sinat_31311947/article/details/53914000

 

getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                //获取View可见区域的bottom
                Rect rect = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                if(bottom!=0 && oldBottom!=0 && bottom - rect.bottom <= 0){
                    Toast.makeText(Main3Activity.this, "隐藏", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(Main3Activity.this, "弹出", Toast.LENGTH_SHORT).show();
                }
            }
        });

 

import android.app.Activity;
import android.arch.lifecycle.GenericLifecycleObserver;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class SoftKeyBoardListener {
    public interface OnSoftKeyBoardChangeListener {
        void keyBoardShow(int height);

        void keyBoardHide();
    }

    private View rootView;//activity的根视图
    private int screenBottom;//纪录根视图的显示高度
    private OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener;
    boolean isShow = false;//软键盘是否显示
    private ViewTreeObserver.OnGlobalLayoutListener listener;

    private SoftKeyBoardListener(Activity activity) {
        int state = WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE & activity.getWindow().getAttributes().softInputMode;
        switch (state) {
            case WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE:
            case WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE:
                isShow = true;
                break;
        }
        //获取activity的根视图
        rootView = activity.getWindow().getDecorView();
        screenBottom = activity.getWindowManager().getDefaultDisplay().getHeight();
        //监听视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变
        listener = new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override

            public void onGlobalLayout() {

                //获取当前根视图在屏幕上显示的大小
                Rect r = new Rect();

                rootView.getWindowVisibleDisplayFrame(r);

                System.out.println("rect============" + isShow + "===" + r.toShortString() + "===" + screenBottom);
                if (!isShow && screenBottom > r.bottom) {
                    isShow = true;
                    if (onSoftKeyBoardChangeListener != null) {
                        onSoftKeyBoardChangeListener.keyBoardShow(screenBottom - r.bottom);
                    }
                    return;
                }

                if (isShow && r.bottom >= screenBottom) {
                    isShow = false;
                    if (onSoftKeyBoardChangeListener != null) {
                        onSoftKeyBoardChangeListener.keyBoardHide();
                    }
                    return;
                }

            }

        };
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(listener);
        addLifeObServer(activity);
    }

    private void setOnSoftKeyBoardChangeListener(OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {

        this.onSoftKeyBoardChangeListener = onSoftKeyBoardChangeListener;

    }

    public static void setListener(Activity activity, OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {

        SoftKeyBoardListener softKeyBoardListener = new SoftKeyBoardListener(activity);

        softKeyBoardListener.setOnSoftKeyBoardChangeListener(onSoftKeyBoardChangeListener);

    }

    public void addLifeObServer(Activity activity) {
        if (activity instanceof LifecycleOwner) {
            LifecycleOwner owner = (LifecycleOwner) activity;
            owner.getLifecycle().addObserver(new GenericLifecycleObserver() {
                @Override
                public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
                    if (event == Lifecycle.Event.ON_DESTROY) {
                        if (rootView != null)
                            rootView.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
                    }
                }
            });
        }
    }


    public static void closeKeybord(EditText mEditText, Context mContext) {

        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);

        mEditText.setFocusable(false);

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Android应用程序中监听软键盘状态并在软键盘打开时将其隐藏,可以使用以下代码: 1. 首先,在你的 activity 的 onCreate 方法中获取根布局并设置以下属性: ``` final View activityRootView = findViewById(R.id.activityRoot); activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight(); if (heightDiff > dpToPx(MyActivity.this, 200)) { // 如果高度差超过 200 dp,就认为软键盘打开了 hideSoftKeyboard(MyActivity.this); // 隐藏软键盘 } } }); ``` 其中,`activityRootView` 是你的 activity 的根布局,`OnGlobalLayoutListener` 是一个监听布局变化的接口,`heightDiff` 是根布局高度和 activity 高度的差值,`dpToPx` 是一个将 dp 转化为 px 的方法,`hideSoftKeyboard` 是将软键盘隐藏的方法。 2. 然后,编写 `dpToPx` 和 `hideSoftKeyboard` 方法: ``` public static int dpToPx(Context context, int dp) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics); } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); View currentFocusView = activity.getCurrentFocus(); if (currentFocusView != null) { inputMethodManager.hideSoftInputFromWindow(currentFocusView.getWindowToken(), 0); } } ``` 其中,`dpToPx` 方法将 dp 转化为 px,`hideSoftKeyboard` 方法接收一个 Activity 对象并使用 `InputMethodManager` 和 `getCurrentFocus` 方法获取当前的焦点视图并将软键盘隐藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值