Skip to content

Instantly share code, notes, and snippets.

@CoderChoy
Last active September 25, 2017 06:10
Show Gist options
  • Save CoderChoy/5621ac673f2eb0dd73579f46770b2d6d to your computer and use it in GitHub Desktop.
Save CoderChoy/5621ac673f2eb0dd73579f46770b2d6d to your computer and use it in GitHub Desktop.
点击EditText之外的区域隐藏键盘
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class SampleActivity extends AppCompatActivity {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View currentFocus = getCurrentFocus();
if (shouldHideSoftInput(currentFocus, ev)) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
currentFocus.clearFocus();
}
}
return super.dispatchTouchEvent(ev);
}
private boolean shouldHideSoftInput(View view, MotionEvent event) {
if (view != null && (view instanceof EditText)) {
int[] leftTop = {0, 0};
view.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + view.getHeight();
int right = left + view.getWidth();
return !(event.getRawX() > left && event.getRawX() < right
&& event.getRawY() > top && event.getRawY() < bottom);
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment