效果
- EdiText默认不获取焦点,点击后进入输入模式,输入法弹出,获取焦点。
- 当输入完成后,输入法隐藏,EditText自动清除焦点。
实现
1、先解决EditText自动获取焦点的问题,在父布局内添加
android:focusable="true"
android:focusableInTouchMode="true"
2、编写自定义EditText
public class EditText_AutoFocus extends androidx.appcompat.widget.AppCompatEditText {
OnEditCompleteListener mOnEditCompleteListener = null;
EditText_AutoFocus editText = this;
public EditText_AutoFocus(Context context) {
super(context);
init();
}
public EditText_AutoFocus(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public EditText_AutoFocus(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
getWindowVisibleDisplayFrame(r);
if ((getRootView().getHeight() - (r.bottom)) < 20) {
//软键盘隐藏
if (isFocused()) {
if (mOnEditCompleteListener != null) {
mOnEditCompleteListener.onEditComplete(editText);
}
clearFocus();
}
}
}
});
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
//焦点发生变化
if (mOnEditCompleteListener != null) {
mOnEditCompleteListener.onEditComplete(editText);
}
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void clearFocus() {
if (mOnEditCompleteListener != null) {
mOnEditCompleteListener.onEditComplete(editText);
}
super.clearFocus();
}
void setOnEditCompleteListener(OnEditCompleteListener onEditCompleteListener) {
this.mOnEditCompleteListener = onEditCompleteListener;
}
interface OnEditCompleteListener {
void onEditComplete(EditText_AutoFocus editText);
}
}