Closing drawer when navigating to current activity - android

I am working with the navigation drawer, and having a small problem. The problem occurs When I am in my an activity, and navigate to that same activity though the navigation drawer. The activity launches new (screen popping up).
I would like the drawer to just close when the user attempts to navigate to the activity they are currently on.
Thanks for you help!

Why not just check the current Activity, pseudocode:
if (this instanceof SomeActivity){
closedrawer();
}else{
navigate to SomeActivity
}

//global reference
private DrawerLayout mDrawerLayout;
//instantiate onCreate()
mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout);
//close it some where, on button click...
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
}

In the method you handle clicks from the navigation drawer:
// This is for the case where the user is trying to open a fragment called `NewFragment`
Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(NewFragment.TAG);
if (currentFragment == null) {
NewFragment newFragment = new NewFragment()
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment, NewFragment.TAG);
transaction.commit();
}
mDrawerLayout.closeDrawer(mDrawerList);
This works if you have added your fragments to the fragment container with the tag. I usually keep this as a public static final String in the respective fragments. For instance, NewFragment has a static String called TAG that is can be used to find it later using the fragment manager.
If the currentFragment is null, it means that is not currently added to the manager's activity nor on the back stack. In that case add the new fragment to the fragment container. If not, just simply close the navigation drawer.

Related

Handle Fragment Backstack According to the Current Fragment

Problem 1
I have a Navigation Drawer and most of my fragment transactions happens from here.
So say I have 4 Items in my drawer and I am doing the transaction from all of them. So if I am at the fragment [A] and now I click on the fragment [B], I need to come back to the previous fragment i.e. [A]. But if I keep clicking on the Item B of the navigation drawer that opens the fragment [B], I keep adding it to the backstack and when I press the back button, I am still at the same fragment.
Problem 2
How do I achieve the Clear Top behavior that is used for the intents for the fragments. As intents have the power to clear the activities from the stack from the top only, I want to achieve the same behavior.
Problem 1 & 2 solution Idea:
Create an Interface say FragmentInstanceHandler
public interface FragmentInstanceHandler {
public void openFragment(Fragment fragment, String fragmentTag);
}
Create a BaseFragment like below and extend this to all your Fragment classes:
public BaseFragment extends Fragment {
public FragmentInstanceHandler fragmentInstanceHandler;
public void setFragmentInstanceHandler(FragmentInstanceHandler fragmentInstanceHandler) {
this.fragmentInstanceHandler = fragmentInstanceHandler;
}
}
Implement the FragmentInstanceHandler interface to the Activity in which you are going to open all the Fragments. Let's say Activity is MainActivity:
public MainActivity extends Activity implements FragmentInstanceHandler {
private BaseFragment currentFragment;
#Override
public void openFragment(BaseFragment fragment, String fragmentTag) {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment oldFragmentInstance = fragmentManager .findFragmentByTag(fragmentTag);
boolean fragmentPopped = fragmentManager.popBackStackImmediate (fragmentTag, 0);
if (!fragmentPopped && oldFragmentInstance == null) {
fragment.setFragmentInstanceHandler(this);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, fragment, fragmentTag);
fragmentTransaction.addToBackStack(fragmentTag);
fragmentTransaction.commit();
currentFragment = fragment;
} else if(fragmentPopped ){
currentFragment = oldFragmentInstance;
}
if(mDrawerLayout!= null)
mDrawerLayout.closeDrawers();
}
}
Now whenever you want to open a new Fragment even from any other Fragment you can call method like below, It is advised to provide new tag if you want to have new instance of same Fragment:
fragmentInstanceHandler.openFragment(new MyFragment(), "FragmentNewInstance");
You can tweak FragmentInstanceHandlerto add your own method to replace the current Fragment instead of adding. Above solution just gives you an idea how you can acheive your solution by putting and mananging all your code from one place.

navigation drawer nested fragments

I've tried almost everything but nothing seems to work. I have a navigation drawer with these fragments, say:
A - viewpager
B - listview
C - listview
Now in B and C, listview are clickable items with each having their own fragments. So ListViewA has a fragment, ListViewB has a fragment.
I want proper back navigation. This is how I'm doing it, when initializing the navigation drawer:
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
And when choosing an option from listview:
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
ft.replace(R.id.frame, new FragmentB(),"HubSettings");
ft.addToBackStack(null);
ft.commit();
If I put addtoBackStack() in both transactions, back navigation works fine but navigation drawer title is not being set properly. I want to disable back button and force changing fragments from navigation drawer so that action bar title is set properly. How do I disable back button when it comes to CFragment?
One can go from menu like:
Navigation Drawer->B Fragment->Listview option 1 Fragment
Pressing Back -> Back to B Fragment -> Disable Back Button
Just override onBackPressed in your Activity which contains the fragments like this:
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count > 0) {
getSupportFragmentManager().popBackStack();
updateDrawerToggle();
}
}

How to remove all fragments except first one?

My application contains AppBaseActivity having NavigationView with few menu items. By default, I load Home fragment & on clicking each menu item from drawer, I open specific fragment.
My problem is, I need keep Home fragment all the time showing if user clicks back button.
Stepwise explanation :
On activity launch, loads Home fragment by default
Suppose selects Menu Item 1, loads related fragment[*4]
Suppose selects Menu Item 2, loads related fragment[*4]
I want to make back stack clear however, keeping Home fragment persistent so that if user presses back button instead of opting menu item from drawer or simply go to any fragment & on killing it, should navigate back to Home fragment.
In my current case, it simply closes/terminates my app.
AppBaseActivity Java (some part of code)
onCreate() {
fragmentTransaction = fragmentManager.beginTransaction();
HomeFragment homeFragment = new HomeFragment();
fragmentTransaction.add(R.id.body_container, homeFragment, getResources().getString(R.string.app_name));
fragmentTransaction.commit();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
navigationView.getMenu().findItem(item.getItemId()).setChecked(true);
switch (item.getItemId()) {
case R.id.nav_terms :
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentTransaction = fragmentManager.beginTransaction();
TCFragment tcFragment = new TCFragment();
fragmentTransaction.add(R.id.body_container, tcFragment, getResources().getString(R.string.tc_screen_name));
fragmentTransaction.commit();
break;
case R.id.nav_about_us :
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentTransaction = fragmentManager.beginTransaction();
AboutUsFragment aboutUsFragment = new AboutUsFragment();
fragmentTransaction.add(R.id.body_container, aboutUsFragment, getResources().getString(R.string.about_us_screen_name));
fragmentTransaction.commit();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
try by adding this line with home fragment before commit:
fragmentTransaction addTobackStack(null);
You need to add the transaction to the backstack using addToBackStack(). The back press would automatically pop the topmost fragment from the backstack.
Refer to
https://developer.android.com/guide/components/fragments.html
The relevant section is "Performing Fragment Transactions"

Call fragment from activity on back pressed?

I am using navigation drawer and fragment to show the component on selecting navigation option.And if user select navigation drawer option a fragment will open. So my problem is when I call a activity from fragment and when I press back button it call previous fragment but the content of that fragment remain same. What I want is when I press back button from activity it should open my fragment or recall fragment and values should be blank like first time we call the fragment.
Thanks.
Try this:-
#Override
public void onBackPressed() {
if (getTitle().equals("Title")) {
YourFragment fragment =new YourFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
} else {
super.onBackPressed();
}
}

Switching between fragments with back button

Ok i have an activity with one main fragment, that has a menu on it. When a user clicks on a menu item another fragment is animated into the screen, with this code:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out);
ft.hide(getFragmentManager().findFragmentByTag("menu_fragment"));
Fragment opisFragment = getFragmentManager().findFragmentByTag("opis_fragment");
if (opisFragment == null) {
opisFragment = new OpisFragment();
ft.add(R.id.p_container, opisFragment, "opis_fragment");
ft.commit();
} else {
ft.show(opisFragment);
}
Note: pr_fragment is the tag of the current fragment, the one that has the menu.
Now, this works well, but when i'm on the second fragment i want to add the functionality, that when the user clicks the back button it will show the first fragment. With this code, when i click back it exits the activity alltogether.
Thank you for the help!
All you need is to use addToBackStack(String name) of FragmentTransaction
// Showing menu fragment also added in backstack
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out)
.add(R.id.p_container, menuFragment, "menu_fragment")
.addToBackStack("menu_fragment")
.commit();
// Showing opis fragment also added in backstack
FragmentTransaction ft2 = getFragmentManager().beginTransaction();
ft2.setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out)
.add(R.id.p_container, opisFragment, "opis_fragment")
.addToBackStack("opis_fragment")
.commit();
Assuming "opis fragment" is in foreground, when you press back button, "menu_fragment" will be displayed back to the foreground, pressing back button again will exit the activity.
With this code, when i click back it exits the activity alltogether.
Normal because there is just your activity in your app stack. the addToBackStack() method is what you are looking for.
if (opisFragment == null) {
opisFragment = new OpisFragment();
ft.add(R.id.p_container, opisFragment, "opis_fragment");
ft.addToBackStack("tag"); // <<< this line
ft.commit();
}
From the doc :
Before you call commit(), however, you might want to call addToBackStack(), in order to add the transaction to a back stack of fragment transactions. This back stack is managed by the activity and allows the user to return to the previous fragment state, by pressing the Back button.
in mainactivity you can check fragments count if fragments count more than one we will show back button
if(getSupportFragmentManager().getBackStackEntryCount() > 0)
{
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
else
{
mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}

Categories

Resources