Save state navigation drawer page (fragment) - android

I've had a search on SO and can't find anything that works.
Here's what I want to do, when I navigate between navigation drawer pages, I want the view to be the same. So if I go from page A to B, and then from B to A. I expect A to have the same state.
In my app, I add some text to fragment A via some button. When I navigate to fragment B, and then back to A, the text is gone. I want the text to still be there.
How do I do this?
I've already tried setRetainState(true). This doesn't work. I have also made sure that new Fragment() is only called once when going to the page. This also doesn't work.
The structure of my navigation drawer is identical to the one shown in the Android documentation.

I think, if you have a navigation drawer that you use fragments for each page.
On select item in navigation drawer don't recreate the fragment, just pop it from back stack if it exists.
HomeFragment homeFragment = (HomeFragment) fm.findFragmentByTag(fragmentName);
if (homeFragment == null) {
homeFragment = new HomeFragment();
fm.beginTransaction().addToBackStack(fragmentName).replace(R.id.content_frame, homeFragment, fragmentName).commit();
} else {
fm.popBackStackImmediate(fragmentName, 0);
}

Related

calling previous fragment from another fragment inside navigation drawer

Hi I have a navigation drawer and I have 4 fragments. I want to go from fragment 3 to fragment 2 on back press and on back press from fragment 4 it should go to fragment 1.How can I do this ??
I have tried adding fragments to back stack. If I add fragment to back stack when I click from home fragment the app should actually close.Instead of closing the fragment which I added to backstack is showing and when back pressing from that it showing the home fragment again and then the app is closing.
//try this code add fragment number while opening new fragment and remove last positions from the list on backpress
public ArrayList<Integer> list = new ArrayList<>();
public void addToStack(int pos)
{
if (!list.contains(pos))
{
list.add(pos);
}
}

Android Navigation Drawer Items linked to Fragments

In my application I created a Navigation Drawer which has 5 items, once an item is clicked in the Navigation Drawer, I can correctly check the item and show the new fragment using the fragment manager.
But currently I have three problems:
My application has floating action buttons, that of course perform actions and open new fragments, so I need to handle that "Fragment changing" in the navigation drawer too, setting as checked the current item which corresponds to the fragment showed.
I SORT OF solved this problem, but using a single method that
performs the fragment transaction in the MainActivity and meanwhile
checks the new item. So everytime a Fragment want to call another
Fragment, it uses this function passing the nav_drawer_item_id as a
parameter. I think that this solutions sucks, so if you have a better idea, it would be really welcome!
My biggest problem is that when the user press the Android Back Button, the fragment pops back to previous one (or sometimes I call popback() programmatically because I am done with that specific fragment )
I really don't know how to solve this problem because I can't check the correct item in the navigation drawer once a fragment is popped back, I need to know which fragment it is.
I need to show the new fragment once the navigation drawer is closed in order to respect "Android Rules" ( And because it's nice ).
I sort of solved this problem too, by setting a "nextFragment" inside the navigation drawer onNavigationItemSelectedListener and by showing the new fragment inside the drawer onDrawerClosed. Is it the only solution?
I'm not posting any code because it really doesn't deserve to be seen, so here is some extra info:
I have a single activity which contains the Navigation Drawer and currently handles the fragment transactions.
I have 6 fragments, 5 called from the Navigation Drawer and 1 called only from others UI components, but this one doesn't need to be checked on the drawer of course.
I tought about a solution and it was like "Setting the checked item FROM the fragment that is showed", but I didn't find any way to get the Navigation Drawer from the Fragment in order to set the proper item checked.
Implement FragmentManager.OnBackStackChangedListener in your activity to get notified whenever something is popped off the back stack and sync the navigation drawer from the callback. That should get rid of the problem caused when the back button is pressed.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.....
getSupportFragmentManager().addOnBackStackChangedListener(this);
}
#Override
public void onBackStackChanged() {
// Get the currently active fragment
Fragment fragment =
getSupportFragmentManager().findFragmentById(R.id.fragments_frame);
// Check which fragment is active, check the
// correct selection and set the title accordingly
if (fragment instanceof FragmentAtPosition0) {
setCheckedAndTitle(0);
} else if (fragment instanceof FragmentAtPosition1) {
setCheckedAndTitle(1);
}
}
private void setCheckedAndTitle(int position) {
MenuItem item = navView.getMenu().getItem(position);
item.setChecked(true);
setTitle(item.getTitle());
}
As for the other two cases that you mentioned, I think the solutions you have mentioned are the preferred ways.

Using Fragments recover Home/Drawer Button

I have an app with a main activity which loads a navigation drawer, and a pair of fragments that load in that activity ...
In the navigation drawer I have 4 options A, B, C and D ... the first one loads FragmentA on my activity and the last 3 load FragmentB ..
FragmentA displays a list of elements and, upon selecting one of these elements FragmentB is used to load its content... I want to change the home (hamburger/drawer) icon on FragmentB for the up icon when initiating from FragmentA (and change the corresponding behavior to make a popstack on select).. I have no problem with this using setDisplayHomeAsUpEnabled(true), but since all this is occurring inside one activity if I then select one other option (say B) from the navigation drawer the up icon will still be showing (it its also showing on the popped fragment)...
if I use setDisplayHomeAsUpEnabled(false) all this do is hide the home/up button from the toolbar, I need to recover the home button and make sure this will be shown when FragmentB is initiated from the drawer menu ...
Does this problem ring a bell to anyone? or am I just using fragments the wrong way? .. any advice will be appreciated
EDIT
this is more or less what I have in code
In Main Activity .. as the onNavigationItemSelected(MenuItem item) for the drawer I have a something like this ...
switch(optionNumber) {
case 0:
fragment = FragmentA.newInstance(optionNumber);
break;
default:
fragment = FragmentB.newInstance(optionNumber);
break;
}
Fragment frag = fragmentManager.findFragmentByTag("current_fragment");
if (frag != null && frag.getClass() == FolderFragment.class){
((FolderFragment)frag).resetScroll();
}
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.content, fragment, "current_fragment").commit();
which selects the fragment to load according to the option selected..
In FragmentA I'm calling FragmentB with this ..
FragmentB fFragment = FragmentB.newInstance(position);
Bundle args = new Bundle();
args.putString("filter", "something"); fFragment.setArguments(args);
mActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.flContent, fFragment, "current_fragment")
.addToBackStack(null)
.commit();
Preserving the fragment in the stack
And in fragmentB inside onResume() function I got something like...
String filter = getArguments().getString("filter", null);
if (type != null) {
mActivity.setTitle(title);
mActivity.getSupportActionBar().setDisplayShowHomeEnabled(true);
}else {
/*mActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mActivity.getSupportActionBar().setDisplayShowHomeEnabled(true);
mActivity.getSupportActionBar().setHomeButtonEnabled(true);
mActivity.getSupportActionBar().setIcon(R.mipmap.ic_menu);*/
}
So When I'm creating fragmentB I check for arguments and see if it comes from fragmentA or not ( I could also check the fragmentmanager backstack and see if there's something)... there I just change the drawer icon with setDisplayShowHomeEnabled(true) ... leaving the back arrow, if I return to FragmentA (via onBackPressed()) FragmentA shows the arrow and I need it to show the original drawer icon ... the same happens if I select an option from the drawer menu ...
Does this gives more clarity to my issue ?... I have some commented code there because it doesn't work .. if I activate the line with setDisplayHomeAsUpEnabled(false).. the icon just disappears from the activity (which is the intended result of the function as far as I know)...
After a while I finally found this post
Switching between Android Navigation Drawer image and Up caret when using fragments
I guess that when involving a Drawer in the interface you might need to handle this issue with that component... this post gave me the answer.
Particular notice to the last comment by Wolfram Rittmeyer

Recreate Fragments on BackKey Pressed

Im trying to Solve a problem where when a user press back key, the fragment should be recreated rather than loading from back stack. I have a single Main activity with a frame layout and i replace the fragments within the single frame dynamically. the code below works when the user go from fragment within fragment. but when the user select from navigation drawer, the replaced fragment is going on to the top of backstack which is causing problems.
Right now the code i wrote in BackKey Pressed Event
public override void OnBackPressed()
{
Android.Support.V4.App.FragmentManager.IBackStackEntry entry =
SupportFragmentManager.GetBackStackEntryAt(SupportFragmentManager.BackStackEntryCount - 1);
string str = entry.Name;
if (SupportFragmentManager.BackStackEntryCount == 0)
{
this.Finish();
}
else
{
Fragment fr = (Fragment)MagicallyCreateInstance(str);
SupportFragmentManager.BeginTransaction().Replace(Resource.Id.content_frame, fr).Commit();
SupportFragmentManager.PopBackStack();
}
base.OnBackPressed();
}
i also have a replace fragment method which i use to replace fragments. but in this process the back key is getting disabled by default somehow (Not sure how) but whenever there is existing fragment in the backstack, the old UI is getting loaded. Can i refresh the layout here?
public void ReplaceFragment(Fragment fragment, FragmentManager fragmentManager)
{
string backStateName = fragment.Class.SimpleName;
bool fragmentPopped = fragmentManager.PopBackStackImmediate(backStateName, 0);
if (!fragmentPopped && fragmentManager.FindFragmentByTag(backStateName) == null)
{
fragmentManager.BeginTransaction()
.Replace(Resource.Id.content_frame, fragment).SetTransitionStyle(FragmentTransaction.TransitFragmentFade)
.AddToBackStack(backStateName)
.Commit();
}
}
Can anyone please help me solve this any one of the above?
I hope I'm understanding your problem correctly. But it sounds like you want to make sure that when the user selects a destination from your main navigation you want to make sure the back stack is cleared or reset.
Ex:
Stack looks like this:
A->B->C
User selects D from main navigation, stack should look like:
D
NOT
A->B->C->D
If this is the case, you should clear the back stack before navigating to any top-level destinations. This can be done like so:
FragmentManager.PopBackStack(null, FragmentManager.PopBackStackInclusive);
The documentation for this method is not great, but it will pop everything off the back stack. A discussion can be found here: https://groups.google.com/d/msg/android-developers/0qXCA9rW7EI/M9riRM0kl9QJ

How to find the currently displayed fragment on android using Xamarin

I'm trying to work out a way to get the currently displayed fragment on a Android app I'm working on. I have a Startup View that loads fragments, what I need to do is display a popup message when the user taps the back button but only when the using is tapping the back button from a certain fragement. For example:
Fragment A > Nav to.. > Fragment B > Nav to... > Fragment C
If the user clicks the back button from fragment C then nothing is displayed and the user goes back to fragment B as expected. But when the user click back on fragment B a popup is displayed asking the user to confirm that action before being allowed to continue back to fragment A, I hope that makes sense.
I know about the OnBackPressed() which I can override on a view but I cant touch that in a fragment. Any pointers would be appreciated.
Hi when you add a new transaction replace use a key TAG
var ft = FragmentManager.BeginTransaction();
ft.Replace(Resource.Id.details, details, "FRAGMENT1");
and if you need to check if the specify fragment is visible
Fragment myFragment = (Fragment)FragmentManager.FindFragmentByTag("FRAGMENT1");
if (myFragment.IsVisible){
//your code here
}
or if you need to get and check all of fragments inside the fragment manager you can use this
var fragmentsarray = FragmentManager.Fragments;
foreach(var fragment in fragmentsarray)
{
if (fragment.IsVisible) {
//put the code to use and get the tag to identify the current Fragment
string tag = fragment.Tag;
}
}
if need more specify Fragments info you can check the Android Docs here http://developer.android.com/reference/android/app/Fragment.html
Hope it helps you

Categories

Resources