问题
In android app, having a few activities with multiple fragments. Those activities or fragment could be running alive even if it's not on the top of the backStack, and receiving notifications from different services.
When some event happens it is required to show a dialog to communicate with user. The activity or fragment on top of the stack may not have the handler for that event. Any other activity or fragment who is interested should react to open one dialog to the user.
The problem is the listeners in the activities and fragments to handle the events independently don't know if there has been already the same dialog displayed.
What is best way to tell whether the handler should open the dialog or not? Since this dialog is same for the same event so it may help if could have it as a singleton.
Anyone have suggestion how to make the dialog a singleton for this type of situation?
回答1:
You can't make Dialog singletone, because Dialogs are linked with current view. And your current view may change - dialog may be sown from different instances of the activities (one or many).
But you can implement a simple singletone class to store all dialog data - save data into onPause
and retrieve it in Dialog's onCreateView
.
So you will get singleton instance with all data, but Dialogs may vary according to current view.
Also you can store a weak link to the shown dialog in that singletone class. Using such method, you can detect is your dialog currently shown or not.
来源:https://stackoverflow.com/questions/36380839/how-to-make-a-sington-dialog