Dialog或DialogFragment中的Activity是否存在dispatchTouchEvent()的等效项

dra*_*sia 4 android dialog touch-event android-dialogfragment

我需要截取应用程序中的所有触摸事件以监视自定义活动超时.

目前我dispatchTouchEvent()在我的活动中使用,但如果我在屏幕上有一个对话框,则不会调用它.有没有人知道我是否有任何方法可以在存在对话框的情况下使用相同的功能?

谢谢

小智 6

对于使用dispatchTouchEvent()在DialogFragment,覆盖onCreateDialog并返回一个自定义的DialogdispatchTouchEvent(在您的自定义DialogFragment).

例如,在DialogFragment中单击外部时关闭键盘:

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new Dialog(getActivity(), getTheme()) {
        @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);
        }

    };
}
Run Code Online (Sandbox Code Playgroud)