7

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

Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
draksia
  • 2,371
  • 2
  • 20
  • 25
  • Did you ever get a answer to this? – TorukMakto Sep 23 '13 at 01:34
  • Nope never did, but I am not working on the project any more. – draksia Sep 26 '13 at 17:03
  • @draksia @Jailbroken I did try this I called `dispatchTouchEvent()` on the `Activity` from the `Dialog`'s `dispatchTouchEvent()`. However implementing this turned a little nasty for me since I found that this does not work for `ListView` and `GridView`'s `OnItemClickListener` i.e. you don't get any callbacks (Only on some devices). All the other views and layouts worked fine though! – Abbas Aug 15 '16 at 09:05
  • Any solution for this issue @Abbas – kishan verma Aug 07 '23 at 13:44

2 Answers2

9

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

    };
}
Joris
  • 486
  • 7
  • 10
2

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

}
Oleksandr Nos
  • 332
  • 5
  • 17