2

I am currently writing a drawer layout as my main layout, with an embedded FrameLayout that I will be using to hold each “page” when an item on the drawer is clicked on. When the app first starts, an initial fragment will be show. Other fragments may be added/replaced later which is fine, however, my problem is that when the user clicks the back button on the very first “initial fragment”, I don’t want that particular fragment to be removed from the layout. Currently, it is being removed and it’s just showing a drawer layout with no other content (which makes sense). I want the app to automatically exit if the initial fragment was the last one showing and the back button is pressed, instead of removing that initial fragment and then after another back press, then it exits.

Things I have thought of doing:

  • Not adding the first fragment to the backstack. (If I do this, I can compare it with the classname of the fragment which is a somewhat longer string, or I can use a boolean value for once the first fragment has been placed (and not added to backstack), the boolean is set which allows the fragments to now be added.
  • Overriding the onBackPressed function of the activity

Does anyone have a suggested way of doing this or can think of a better way? Thanks

Michael
  • 83
  • 9

2 Answers2

3

The first bullet point sounds the cleanest. You have no other need to handle conditions when back is hit, correct? If that's the case, it's less lines of code (removing one as opposed to adding several) and you get to keep default Activity methods as is.

I know that's not exactly what you asked, but I think the first bullet point is so clean, that I just wouldn't try something else.

dpants
  • 86
  • 4
  • Actually, that is what I was asking about, and I think is helpful. Going to wait to accept an answer to see if anything else comes up. Thanks – Michael May 04 '17 at 17:28
0

I have implemented same in one of the app using my own Stack of fragment. and also implemented onBackPressed method.

Every time when user clicks on item in drawer i add fragment in stack and in back press once its length is 1 I finish the activity with message.

On item click -- Add/replace fragment in container.

OnBackPressed -- Pop fragments from stack and once its last one i finish activity.

Hope this can give you another option to consider.

Wasim K. Memon
  • 5,979
  • 4
  • 40
  • 55