Android EditText监听焦点事件

EditText et_1;

et_1.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 处理获得焦点后的事件
                }
            }
        });

可转载此文章,但请注明出处。
作者:OAOAAce
QQ群:289324199 【欢迎加入一起探讨Android技术】

Android监听 EditText 相关的软键盘状态变化,可以通过多种方式实现,具体取决于使用场景和布局结构。以下是几种常见且有效的实现方法: ### 3.1 使用 ViewTreeObserver 监听全局布局变化 通过监听 `ViewTreeObserver` 的 `OnGlobalLayoutListener`,可以检测页面根视图高度的变化,从而判断软键盘是否弹出或收起。该方法适用于 Activity 或 Fragment 中的主布局,但不适用于 Dialog 或 PopupWindow 等浮动窗口。 ```java View rootView = findViewById(R.id.root_layout); rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect rect = new Rect(); rootView.getWindowVisibleDisplayFrame(rect); int screenHeight = rootView.getRootView().getHeight(); int keyboardHeight = screenHeight - (rect.bottom - rect.top); if (keyboardHeight > 100) { // 软键盘弹出 } else { // 软键盘收起 } } }); ``` 该方法通过比较根视图的实际高度与可见区域的高度差来判断软键盘是否显示。若差值大于 100 像素,则认为软键盘已弹出 [^3]。 ### 3.2 在 Dialog 中监听软键盘状态 当使用 Dialog 或 PopupWindow 时,由于 Dialog 弹出后整个页面高度已经改变,无法直接使用 `ViewTreeObserver` 来监听软键盘状态。此时应通过监听 Dialog 内容视图的 `OnApplyWindowInsetsListener` 或 `OnGlobalLayoutListener` 来判断软键盘是否弹出。 ```java Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.dialog_with_edittext); EditText editText = dialog.findViewById(R.id.edit_text); View contentView = dialog.findViewById(android.R.id.content); contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect rect = new Rect(); contentView.getWindowVisibleDisplayFrame(rect); int screenHeight = contentView.getRootView().getHeight(); int keyboardHeight = screenHeight - (rect.bottom - rect.top); if (keyboardHeight > 100) { // 软键盘弹出,调整 Dialog 位置 } else { // 软键盘收起,恢复 Dialog 位置 } } }); ``` 该方法适用于 Dialog 或浮动窗口,通过监听其内容视图的高度变化来动态调整布局或 Dialog 的位置 [^2]。 ### 3.3 使用软键盘监听库简化实现 为了简化监听软键盘状态的实现,可以使用开源库如 `SoftKeyboardDetector` 或 `KeyboardVisibilityEvent`,这些库封装了底层监听逻辑,提供更简洁的 API。 例如使用 `KeyboardVisibilityEvent`: ```java KeyboardVisibilityEvent.setEventListener( this, // Activity isOpen -> { if (isOpen) { // 软键盘弹出 } else { // 软键盘收起 } } ); ``` 该库通过监听全局布局变化和窗口焦点变化,提供统一的接口来获取软键盘状态,适用于大多数场景 [^1]。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值