Android: Cancel DialogFragment when using AlertDialog.Builder
Fragments and all the new stuff Android 4 introduced (actually Android 3, but that wasn't available for all devices types)?
I hope you have, because using the new API will allow you to create modern Android apps consistent with the Android 4 design guidelines. Using Fragments is especially useful when developing a single app for multiple device types, like smartphones and tablets.
If you already did and wanted to display a Dialog using the previously encouraged method Activity.showDialog, you will have seen, that the Android developer team deprecated that method (in API level 13 already!). You can still use it, but you shouldn't – even though Android is supposed to be backwards compatible, Google could decide to actually drop support for those methods sometime in the future ;)
The new way is to use DialogFragments which can be displayed as the floating dialog window we already know, but you can also embed it in larger UIs as a normal fragment, if desired. Instead of directly creating Dialog classes/instances you should use the DialogFragment APIs to create and manage them. There's already a great tutorial on the Android developer page, so I will just quickly tell you how the basics work and then finally tell you about the problem I described in the title of this blog post ;)
In order to implement such a DialogFragment, you create a new class which extends from said class and in the onCreateDialog method you can create your Dialog as you're used to – usually by using AlertDialog.Builder. Usually you combine it by defining some kind of DialogListener-Interface to pass back events to the Dialog's host (which is also described in the tutorial).
And this is where the problem started. By using the AlertDialog.Builder and defining the callback interface I had no problem sending those events when displaying a list dialog and selecting an item. This works by using the Builder.setAdapter method and the DialogInterface.OnClickListener listener. Adding an Builder.setOnCancelListener on the other hand, didn't work. It never even fired.
The solution is simple but in my opinion not obvious: override the DialogFragment.onCancel method. Simple as that ;)
So this method is actually there for a reason but why the setOnCancelListener method is not deprecated, when it won't work using the new and highly encouraged DialogFragment, I cannot explain? Maybe Google has their reasons or it's actually a bug nobody really cares about (let's hope Google cares about the missing December bug in the people app ;).
Hope that helped, if you ever ran into this problem and don't forget to like/+1/reshare and comment ;)
PS. don't forget to check out the Android support library as well as the awesome project ActionBarSherlock to give user, who are stuck with devices running older Android versions, the same great user experience.