-2

在警报对话框隐藏键盘的外部单击但对话框应保持不变,我正在检查运动事件但不工作

@Override
 public boolean dispatchTouchEvent(MotionEvent ev) {
View v = getCurrentFocus();

if (v != null && 
        (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == 
MotionEvent.ACTION_MOVE) && 
        v instanceof EditText && 
        !v.getClass().getName().startsWith("android.webkit.")) {
    int scrcoords[] = new int[2];
    v.getLocationOnScreen(scrcoords);
    float x = ev.getRawX() + v.getLeft() - scrcoords[0];
    float y = ev.getRawY() + v.getTop() - scrcoords[1];

    if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom())
        hideKeyboard(this);
}
    return super.dispatchTouchEvent(ev);
}

隐藏键盘

 public static void hideKeyboard(Activity activity) {
if (activity != null && activity.getWindow() != null && activity.getWindow().getDecorView() != null) {
    InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
  }
}
4

1 回答 1

1

您可以使用对话框而不是警报对话框可以执行以下操作。

public void showNotAvailableDialog() {
        final EditText input = new EditText(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        input.setLayoutParams(lp);
        Dialog dialog= new Dialog(this) {
            @Override
            public boolean dispatchTouchEvent(@NonNull MotionEvent motionEvent) {
                if (getCurrentFocus() != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                }
                return super.dispatchTouchEvent(motionEvent);
            }
        };
        dialog.setCanceledOnTouchOutside(false);
        dialog.setContentView(input);
        dialog.show();
    }
于 2018-03-20T11:07:45.167 回答