dialog.findViewById within onPrepareDialog returns null after screen rotation
I have a dialog which shows dynamic content each time it is shown. As such, I have used onPrepareDialog, and in there I use dialog.findViewById() to find the view (an image, in this case).
This code works perfectly until you rotate the device. At that point, the Activity is re-created (as expected), but the next time you try to show the dialog, findViewById returns null.
I am targeting API 7 (2.1). Does anyone have any ideas why this is happening? Thanks.
-- EDIT since i can't answer my own question.. -- Well, for anyone else running into this problem, it's because after rotation it seems like the contentView is no longer valid on the dialog. Of course, onCreateDialog would fix that, but it's not called.. the only way I found to fix this is to set a flag when you show the dialog, and then add the following code (or similar):
@Override
protected void onResume()
{
super.onResum开发者_StackOverflow社区e();
// Destroy the dialog if it was showing during a rotation.
if (YourActivity.isDialogShowing)
{
removeDialog(DIALOG_ID);
YourActivity.isDialogShowing = false;
}
}
This successfully stops the null findViewById's that occur, as onCreateDialog will thus be called on the next usage. I don't understand why there's no documentation about this. Please note that dismissDialog() is not enough, it must be removed.
精彩评论