How to Handle Navigation between Dependent Activities

左心房为你撑大大i 提交于 2019-12-11 19:48:05

问题


My question is how to update an activity based on its child while maintaining the context supplied by its parent.

See the example hierarchy below. There is a flow up and down. Using the app would go something like this:

Select Team 1 on the Home activity --> Activity A inflates based on the selection.
Select Player 2 on Activity A --> Activity B inflates based on the selection.
Select to Add a Stat on Activity B --> Activity C inflates and allows a stat to be added.

User returns to Activity B, which must maintain the Player 2 context and update based on C.
User returns to Activity A, which must maintain the Team 1 context and updated based on B.
User returns to Home, which must update based on A.

Both Activities A and B inflate based on parent selections, but must update if a change is made in a child activity.

For example, let's focus on Activity B. It knows to inflate for Player 1 because this info was passed from Activity A in an intent.

  1. If I were to go to Activity C and press Back, B wouldn't update.
  2. If I were to go to C and press Up, B would crash because it would try to make a new instance and wouldn't know what player to inflate (defined in onCreate()).

I tried declaring B with a "singleTop" launchMode, but then it just restarts and doesn't update based on C's info. Based on my limited experience/research, I see the following options.

  1. Store an Activity's inflater variables as static (so they won't be "lost" when creating a new instance)
  2. Initiate my view inflation (via Fragment) in the Activity's onStart() method so that it would refresh when Restarting. (Would this help? What about the fact that all of my inflation happens inside of a fragment? I fear the Lifecycle gods.)

I'm new to a lot of this and would appreciate any help. Thanks!

EDIT: I've tried making "player" a static variable in Activity B and letting Activity A set it. This seems to be working. I can remove the "singleTop" launch mode and then navigating up from C loads a new instance of B with the info refreshed.

However, this feels like a workaround and I would like someone to comment on this approach and maybe offer an alternative. Thanks.


回答1:


Have you considered using fragments and your home activity handling all the transaction and backstack with arguments and calls to fragment internal methods to update UI?

If you really like to use activities, then you should use start activity for result. You can pass result to calling-activity and update accordingly.

Getting a Result from an Activity



来源:https://stackoverflow.com/questions/23347182/how-to-handle-navigation-between-dependent-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!