简体   繁体   中英

Using android activities and fragments the right way

I need some best practices ideas for my app. I think there is too much boilerplate code right now and I don't know if I'm using activities and fragments the right way.

There are 3 activities (A,B,C). The app starts at A. I can navigate to B which is a simple list and each of the items are clickable to show the item more detailed in activity C. A should be the "root" activity, so I set the parent activities in the manifest file.

Now I want to have a DrawerLayout navigation on B and C, which actually represents A in a smaller way.

I created an abstract NavigationActivity class for taking the view of the activity and set is as the first child of the DrawerLayout and add the navigation as second child. This works very well, but since the navigation has a state I embed the navigation as fragment, because I thought that the state is shared then, but it isn't and I don't know why I should use fragments at all.

Should I use one activity and load different fragments as main content? Then my app consists of 2 activities and maybe 50 fragments, when I finished it. I think that the way I try to implement it is not correct.

As an example: When you enter the PlayStore, there is the navigation on the left. You can browse the app and so on. Do you thing/know that it's the same activity with different main content or are there more activities?

Can you help me? Thanks :)

Single Activity applications are possible, but are not necessarily a best practice. IMHO, fragments have a very complicated lifecycle, so use Activituies when you don't HAVE to use fragments.

If your problem is to share the state of your drawer fragment through activities, you could pass it as an extra to each activity, or keep it in a static class/variable to retrieve it at every start.

Don't forget to also save this state during the destruction of one of your activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM