Fragment Toolbar.

Manage it better.

Piotr Mądry
Aug 22, 2017 · 3 min read

Introduction

Since I started work commercially I met an opinion that working with Fragments is not always intuitive, at least not as much as working with Activities. Especially after watching this video your mindset in context of Fragments might change significantly. Complicated lifecycle, hard management will not change the way of thinking about it.

Toolbar for Fragment. What is wrong with it ?

Let’s assume that we have only one Activity with bottom navigation and the rest of views are Fragments. Normally on every Fragment change toolbar is set as supportActionBar which gives you possibilities to use methods to create, prepare, manage toolbar options menu. It looks simple, doesn’t it?
But it also creates some problems:

  • If you are clearing it, indeed you are losing state and all data.
  • When you are going back to previous Fragments you have to recreate whole action bar.

What is the solution ?

Assuming that we have few types of toolbar in app, you can build it using Builder Pattern and handle all cases in one place. All work comes down to choosing options for your Toolbar.

Summary

Everyone knows how much time we spend on adding menu options and how many lines in code we need to write or copy/paste. This solution saves your time and keeps code clean. No need to set toolbar as supportActionBar. You don’t have to worry about keeping state and data for menu when Fragment changes (it lives as long as your Fragment). To sum up, management is as simple as possible and fragmentManager backstack changes (adding / removing Fragments) has no effect on toolbar at all.

AppUnite collection

We teach how to write apps

)

Thanks to Maciej Ulatowski

Piotr Mądry

Written by

Android Developer® @Appunite

AppUnite collection

We teach how to write apps

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade