Is there an equivalent for dispatchTouchEvent() from Activity in Dialog or DialogFragment

无人久伴 提交于 2019-12-01 04:32:07

问题


I need to intercept all touch events in the application to monitor for a custom activity time out.

Currently I use dispatchTouchEvent() in my activities but this is not called if I have a dialog on the screen. Does any one know if there any way I can have this same functionality with a dialog being present?

Thanks


回答1:


For use dispatchTouchEvent() in DialogFragment, override onCreateDialog and return a custom Dialog with dispatchTouchEvent (in your custom DialogFragment).

Exemple, for dismiss keyboard when click outside in 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);
        }

    };
}


来源:https://stackoverflow.com/questions/16024297/is-there-an-equivalent-for-dispatchtouchevent-from-activity-in-dialog-or-dialo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!