Is there some weakness to the simpler approach of calling Activity.method() from DialogFragment, rather than setting up a listener?

StackOverflow https://stackoverflow.com/questions/15794455

Domanda

After the user requests to delete a file (through a context menu), a DialogFragment is triggered to ask the user to confirm. If the user does confirm, the file is deleted by the calling Activity.

There are at least two ways for doing this.

  1. The DialogFragment calls deleteFile(), a method in the Activity, itself accessible through getActivity().
  2. The Activity implements a DeleteFile interface. The DialogFragment sets up a Uri, initializes the listener to be the Activity, and sends a message to the listener. For additional safety, onAttach() confirms that the Activity does implement the requisite interface.

The documentation suggests that the second option is superior, at least generally. But in this case the first approach seems perfectly robust no matter when the user has triggered a rotation (which resets both the Activity and the DialogFragment).

Is the first approach perfectly adequate, or is there a scenario other than rotation that makes the second approach better.

È stato utile?

Soluzione

Both implementations can accomplish what you're trying to do, but there are certainly some differences between the two. In most cases, interfaces are not completely "necessary", you can always cast to a concrete class and call a method. The benefit interfaces provide is in decoupling. If you use an interface, the DialogFragment is not tied to a specific Activity. Any Activity could implement the same interface and be used with the DialogFragment, making that Fragment more reusable (which is half of the point of fragments).

Altri suggerimenti

I'd say that both implementations are equivalent, given that both of them require the activity to adhere to a specific contract (the class in the first case, the interface in the second). You can't avoid to cast the activity to the specific interface / class.

Another approach you could try is to have (most) of the logic implemented in the fragment itself. I don't know if it suits your case but it would certainly help you in reusing the fragment. Maybe it's less suitable for dialogfragments..

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top