900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Android 监听软键盘弹出/隐藏 控制软键盘弹出/隐藏

Android 监听软键盘弹出/隐藏 控制软键盘弹出/隐藏

时间:2021-03-29 05:56:09

相关推荐

Android 监听软键盘弹出/隐藏 控制软键盘弹出/隐藏

使用环境:

需要控件软键盘时;

使用方法:

输入框的弹出/隐藏监听

/*** 显示软键盘 隐藏删除* 隐藏软键盘 显示删除*/SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {@Overridepublic void keyBoardShow(int height) {LogUtil.e("键盘弹出");}@Overridepublic void keyBoardHide(int height) {LogUtil.e("键盘隐藏");}});

public class SoftKeyBoardListener {private View rootView;//activity的根视图int rootViewVisibleHeight;//纪录根视图的显示高度private OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener;public SoftKeyBoardListener(Activity activity) {//获取activity的根视图rootView = activity.getWindow().getDecorView();//监听视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {//获取当前根视图在屏幕上显示的大小Rect r = new Rect();rootView.getWindowVisibleDisplayFrame(r);int visibleHeight = r.height();System.out.println(""+visibleHeight);if (rootViewVisibleHeight == 0) {rootViewVisibleHeight = visibleHeight;return;}//根视图显示高度没有变化,可以看作软键盘显示/隐藏状态没有改变if (rootViewVisibleHeight == visibleHeight) {return;}//根视图显示高度变小超过200,可以看作软键盘显示了if (rootViewVisibleHeight - visibleHeight > 200) {if (onSoftKeyBoardChangeListener != null) {onSoftKeyBoardChangeListener.keyBoardShow(rootViewVisibleHeight - visibleHeight);}rootViewVisibleHeight = visibleHeight;return;}//根视图显示高度变大超过200,可以看作软键盘隐藏了if (visibleHeight - rootViewVisibleHeight > 200) {if (onSoftKeyBoardChangeListener != null) {onSoftKeyBoardChangeListener.keyBoardHide(visibleHeight - rootViewVisibleHeight);}rootViewVisibleHeight = visibleHeight;return;}}});}private void setOnSoftKeyBoardChangeListener(OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {this.onSoftKeyBoardChangeListener = onSoftKeyBoardChangeListener;}public interface OnSoftKeyBoardChangeListener {void keyBoardShow(int height);void keyBoardHide(int height);}public static void setListener(Activity activity, OnSoftKeyBoardChangeListener onSoftKeyBoardChangeListener) {SoftKeyBoardListener softKeyBoardListener = new SoftKeyBoardListener(activity);softKeyBoardListener.setOnSoftKeyBoardChangeListener(onSoftKeyBoardChangeListener);}}

关闭或者显示输入框的方法

import android.content.Context;import android.view.inputmethod.InputMethodManager;public class KeyBroadUtils {public static void showOrHide(Context context) {InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);}}

有了监听,有了关闭和显示的方法,输入框岂不是随你操作?

更多讨论,欢迎来询问:88627109

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。