关于EditText焦点监听

最近开发关于聊天界面,涉及到EditText的焦点获取和失去来控制页面中相关部分以及虚拟键盘的显示和隐藏。每次遇到这样的需求都要去Google或者Baidu,而且往往花费了时间却没有得到满意的答案。

第一步:进入到页面后我们默认EditText的父容器获的焦点

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:gravity="center">

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:layout_weight="1"
        android:background="#00000000"
        android:hint="input you content"
        android:textColor="#1E1F28"
        android:textColorHint="#ACAEC4"
        android:textSize="14sp" />
</LinearLayout>复制代码

这样操作的目的是避免已进入页面就弹出虚拟键盘,同时也是为了满足我们的需求

第二步:我们需要EditText监听OnFocusChangeListener

contentEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                //获取焦点
            }else{
                //失去焦点
            }
        }
    });复制代码

当我们点击EditText输入框是我们会调用OnFocusChangeListener的onFocusChange方法,hasFocus参数返回true,通常这时候我们也会弹出虚拟键盘

监听了EditText获取焦点,那怎样失去焦点呢?

不要着急,一步步来。。。

最后:失去焦点

contentEdit.cleanFocus();复制代码

失去焦点后,第二步中的onFocusChange方法返回hasFocus为false,这一步我们可以操作虚拟键盘隐藏。

注意:如果没有操作contentEdit.cleanFocus()方法,onFocusChange只有在第一次获取焦点后调用,后面就不会在调用,通常就是这部分容易忽略,往往就满足不了我们的要求

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值