最近开发关于聊天界面,涉及到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只有在第一次获取焦点后调用,后面就不会在调用,通常就是这部分容易忽略,往往就满足不了我们的要求