sponsored links

Android 点击任意位置隐藏

public class AutoHideIMEFrameLayoutextends 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(MotionEventev) {

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(ViewfocusView, MotionEvent event) {

Rect rect = new Rect();

focusView.getHitRect(rect);

if(rect.contains((int)event.getX(), (int)event.getY())) {

return false;

}

return true;

}

private void hideInputMethod(ViewcurrentFocus) {

if (currentFocus == null) { return;}

InputMethodManager imm = (InputMethodManager) currentFocus.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(currentFocus.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

}

}
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();

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));

}

}

activity 和fragment  初始化

 HideIMEUtil.wrap(this);