Keep view state when navigating back to a view

Hi I am using the Navigator in my application to navigate to views. Is there a way to let the user use the back button to navigate to a state the view was previously in. For example, the user may click a button that shows a hidden layout, but if they go to another view, and then try to go back, the view will go to the initial state without the hidden layout. Thanks for any help.

You can reuse the view instances, paying the price in higher memory usage. There are two “default” ways to add a view to a Navigator:


addView(String, View)
addView(String, Class<? extends View>)

Using the former method, you can build a View once and then it’s reused, with its state intact, every time the view is entered (its enter() method is called every time, though!).

You can also add more complex reuse schemes by writing a custom ViewProvider.

Or you can use uri fragments to remember the state and restore the state from it (see
11.9.3. Handling URI Fragment Path
in
11.9. Navigating in an Application
).

Thanks guys. So I guess the issue is that even when the browser back button is used it triggers the view’s enter() method which is where most of the code is.

I use the uri fragments for querying type stuff to carry params to other views, but it seems kindof cumbersome to use for view states where just some components are changing, but maybe that would be the easiest option?

Yes, I should have elaborated that enter() is indeed invoked every time the view is shown; so you might want to build the view content in the View constructor instead. Or if you want to do it lazily (which, in case of complex views, will speed up the application startup), have a boolean field and check it in enter(). Only building the view once will also speed up subsequent view changes, obviously.

As to the granularity of the state stored in the URI, it’s always a judgement call. I, for one, prefer clean UIs that only reflect high-level application state, but your mileage may vary.