Well, it turns out that, every time you call AndroidSupportInjection.inject(this), you're going to end up with a new thing. Our host activity can get destroyed and recreated all it likes, but our retained fragment will only get created once. ![]() Let's assume that the whole reason we want a retained fragment is so that thing will be immune to device rotation. Now that that's out of the way, let's just assume we already have a retained fragment, and we're not going to refactor it away anytime soon - so how do we inject it, and why is it any different than injecting a normal fragment? While they may seem to solve an important problem (retaining state across rotations), they do so at the cost of your sanity. Injecting a Retained Fragment, or, Never Inject Something Twiceįirst we should get this out of the way: you should probably avoid using retained fragments. ![]() Therefore, we need the view model factory for the back-navigation case when we do need to create a new view model. However, during back navigation, when the fragment is created first, that map.get(activity) call returns null and we're out of luck. This is because the Android framework actually instantiates and attaches the fragment before finishing the onCreate of our activity! The above code works the first time because the view model has already been created and is keyed to the activity - meaning we're just getting an existing view model from a Map. If we navigate back to this fragment sometime later, our app will crash. ![]() Hint: remember what I said earlier about the framework calling our fragment's default constructor? One time it does that is during back navigation. I get my ViewModel as expected, the app doesn't crash. Enter fullscreen mode Exit fullscreen mode
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |