Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 789
draksia Avatar asked Apr 15 '13 20:04

draksia


2 Answers

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

    };
}
like image 70
Joris Avatar answered Oct 08 '22 20:10

Joris


Enjoy a Kotlin version everyone:

abstract class BaseDialogFragment : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return object : Dialog(requireContext()){
            override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
                // do your thing here
                return super.dispatchTouchEvent(ev)
            }
        }
    }

}
like image 29
Oleksandr Nos Avatar answered Oct 08 '22 22:10

Oleksandr Nos