xxtesaxx xxtesaxx - 1 month ago 14
Android Question

How to handle configuration change in Snackbar?

I'm facing an issue which hopefully you can help me to fix. In my Android app, I display a Snackbar using the usual way (

Snackbar.make().show()
). However, I also have to deal with configuration changes (like orientation changes from portrait to landscape).

Now if the configuration changes, the Snackbar disappears, which is nothing I wouldn't expect. I had the same issue with ProgressDialog and AlertDialog, which I solved by using a custom subclass of DialogFragment.

I also had this issue with my AsyncTasks which I solved by using a custom subclass of Fragment which I retain (
setRetainInstance(true)
in
onCreate()
of the Fragment) and which keeps a reference to my AsyncTask. In both cases, each Fragment has a callback interface which the Activity has to implement and I set/unset the callback during
onAttach()
/
onDetach()
.

However, Snackbar seems to be different because it is attached to a View instead of a Context like for example the ProgressDialog (in
getDialog()
of my DialogFragment I can use new
ProgressDialog(getActivity())
).

So when and how shall I display a Snackbar after a configuration change? Is using a Fragment the way to go or should I try to work around this by having some private variables on my Activity which I save/restore via the
savedInstanceState
?

Answer

Since no suitable answer was provided and I had to meet a deadline, I now went with the following solution:

  • Create a activiy base class which extends AppCompatAcitity and from which all my activies inherit
  • In the activity base class, create a bunch of instance variables to store information about the Snackbar (isShowing, identifier, message, action, arguments)
  • In the activity base class, create a method to show the snackbar, giving it all the previously mentioned variables
  • In the activity base class, use onSaveInstanceState and onRestoreInstanceState to save/restore the previously mentioned variables
  • If the Snackbar was showing before the configuration change, the boolean will be saved and restored and I can use it to create a new Snackbar with the same configuration in onRestore() of my activity base class
  • When creating the snackbar, I use the snackbar.setCallback() to set a callback where I check if the snackbar was dismissed and if so, I change the isShowing to false
  • When setting up the snackbar, I set the action to call a method in my activiy base class using the identifier I previously provided as an argument to check which Snackbar is was clicked
Comments