一:
AutoHideIMEFrameLayout.java:
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
public class AutoHideIMEFrameLayout extends FrameLayout {
public AutoHideIMEFrameLayout(Context context) {
super(context);
}
public AutoHideIMEFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AutoHideIMEFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
Context context = getContext();
if (context == null || !(context instanceof Activity)) {
return super.dispatchTouchEvent(ev);
}
Activity activity = (Activity) context;
View focusView = activity.getCurrentFocus();
if (focusView != null && shouldHideInputMethod(focusView, ev)) {
hideInputMethod(focusView);
}
}
return super.dispatchTouchEvent(ev);
}
private boolean shouldHideInputMethod(View focusView, MotionEvent event) {
Rect rect = new Rect();
focusView.getHitRect(rect);
return !rect.contains((int) event.getX(), (int) event.getY());
}
private void hideInputMethod(View currentFocus) {
if (currentFocus == null) {
return;
}
InputMethodManager imm = (InputMethodManager) currentFocus.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
HideIMEUtil.java:
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
public class HideIMEUtil {
public static void wrap(Activity activity) {
ViewGroup contentParent = (ViewGroup) activity.findViewById(android.R.id.content);
wrap(contentParent);
}
public static void wrap(Fragment fragment) {
ViewGroup contentParent = (ViewGroup) fragment.getView().getParent();
if (contentParent!=null){
wrap(contentParent);
}
}
public static void wrap(ViewGroup contentParent) {
View content = contentParent.getChildAt(0);
contentParent.removeView(content);
ViewGroup.LayoutParams p = content.getLayoutParams();
AutoHideIMEFrameLayout layout = new AutoHideIMEFrameLayout(content.getContext());
layout.addView(content);
contentParent.addView(layout, new ViewGroup.LayoutParams(p.width, p.height));
}
}
在fragment中,添加一行代码
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
this.inflater=inflater;
this.container=container;
view =inflater.inflate(R.layout.xxx,container,false);
HideIMEUtil.wrap(Objects.requireNonNull(getActivity()));//键盘管理,点击除editText外区域收起键盘
}
如此便实现了点击edittext以外的位置,键盘收回。
二:
在这个布局所在的Activity中加一个属性,键盘就会覆盖屏幕:
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustPan" />
参考:
https://blog.csdn.net/super_cmf_no1/article/details/53406334