So after a long long time there is a post on android. Starting today I will post atleast one trick per week that may ease your day to day android development task.
Before I start my first trick, I am assuming you are already familiar with fragments development in android and already know about action items. If not I suggest you head first to this android guide .
When developing with fragments where your fragments needs to have some specific menus we already use
and than we override needed methods to work with menus right? This is the way to add menus to activity from fragments.
But what if we want to open a new fragment B from our already opened fragment A and our newly opened fragment does not need a menu. And letting menu from fragment A be visible can lead to some serious issues. In such cases we can not let such menus be visible right?
Unfortunately fragments have sort of one-way communications with activity when it comes for menus. Fragments can add any menus they like. But can not remove if they don’t need. Without calling setHasOptionsMenu we can not get callback to fragments method. And we are not doing in fragment B because it’s not needed there. Thus we are helpless here right?..
No fortunately fragments api is not a one-way communication as long as parent activity or any other fragment is involved. In our case we can do the following.
1. When adding fragment B from fragment A. add this line in frag A.
Here targetCode can be anything you like. It can work like startActivityForResult();
2. Now from fragment B our previous fragment A can be accessed by calling
3. In onResume of fragment B call
This will hide any menu from fragments, note that the menu added from activity is still visible (which was in-fact my need of time)
4. In onStop of fragment A call
this will let menu from fragment A be visible when B is leaving. If it’s going back from B to A old menus from A can be visible.
Thats all folks.
Next time we will meet with some more tricks and tips.