Question

Is there a better way to implement a GestureDetetor to all activities instead of having to define a GestureDetector individually?

In my scenario I have 10 activities for which I would like all of them to have the same behavior for Gestures. For example a swipe to the right will end the current activity and take the user back to the main activity.

My options seem to be

  1. Define the GestureDetector in each of my 10 activities
    or
  2. Extend Activity and add a GestureDetector there and then extend from my custom activity.

Is there a better way to implement this behavior?

Was it helpful?

Solution

One easy way to do it is setting the GestureDetector in a base class that all activities extend from. This is a typical approach but it creates a new instance each time.

Another way to do it, depending on your target api, is using Application.registerActivityLifecycleCallbacks. You can find more information in the Application class documentation. This is api 14+.

Don't forget to read the docs:

public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)

Add a new ComponentCallbacks to the base application of the Context, which will be called at the same times as the ComponentCallbacks methods of activities and other components are called. Note that you must be sure to use unregisterComponentCallbacks(ComponentCallbacks) when appropriate in the future; this will not be removed for you.

After you do that, just check ActivityLifecycleCallbacks for more information. You've got all the typical onCreate, start, resume, etc callbacks with the corresponding activity as an argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top