Fragment Animation in when popBackStackImmediate() method used - android

How to load animation when backstack fragment or removing fragment in stack?
I am using below code for remove fragment but i don't know how to add setCustomAnimation method to Load animation.
//Remove fragment in stack
private boolean returnBackStackImmediate(FragmentManager fm) {
List<Fragment> fragments = fm.getFragments();
if (fragments != null && fragments.size() > 0) {
for (Fragment fragment : fragments) {
if (fragment.getChildFragmentManager().getBackStackEntryCount() > 0) {
if (fragment.getChildFragmentManager()
.popBackStackImmediate()) {
Log.d("tag", "CalledInside");
return true;
} else {
return returnBackStackImmediate(fragment
.getChildFragmentManager());
}
}
}
}
return false;
}

Related

Showing the first fragment after returning from the next tab

I use ViewPager and Tabs. I have 3 tabs and in the first tab (Tab_1) I switch from FragmentA to FragmentB. Then I pass to the second tab (Tab_2). After that I return to Tab_1. Actually, it is the fragmentB that is showing but I want fragmentA to show when I return from Tab_2 to Tab_1. I want to have the same behavior when in tab1, I switch from FragmentA to FragmentB and if I pass to Tab_3 and return to Tab_1, it is the FragmentA that is showing. How can I do that?
Did you try SetCurrentItem(int i) for ViewPager on Call of OnResume()
in mainActivity add addtoBackStack method.follow below code.
private void loadfragment(Fragment fragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.addToBackStack("");
fragmentTransaction.commit();
}
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStackImmediate();
} else {
super.onBackPressed();
}
You can create a baseFragment which handles the back press navigation logic and extends that fragment to your fragment
public abstract class BackStackFragment extends Fragment {
public static boolean handleBackPressed(FragmentManager fm)
{
if(fm.getFragments() != null){
for(Fragment frag : fm.getFragments()){
if(frag != null && frag.isVisible() && frag instanceof BackStackFragment){
if(((BackStackFragment)frag).onBackPressed()){
return true;
}
}
}
}
return false;
}
protected boolean onBackPressed()
{
FragmentManager fm = getChildFragmentManager();
if(handleBackPressed(fm)){
return true;
} else if(getUserVisibleHint() && fm.getBackStackEntryCount() > 0){
fm.popBackStack();
return true;
}
return false;
}
}
https://medium.com/#nilan/separate-back-navigation-for-a-tabbed-view-pager-in-android-459859f607e4
In above link, they have explained how to handle the tablayout and the back navigation of tablayout and change the fragment on backpressed

Null object reference in .onBackPressed()

I have fatal exception in the method onBackPressed(): on a null object reference.
How to handle the exception correctly?
My code:
#Override
public void onBackPressed() {
List fragments = getSupportFragmentManager().getFragments();
BaseExampleFragment currentFragment = (BaseExampleFragment) fragments.get(fragments.size() - 1);
if (fragments != null && !currentFragment.onActivityBackPress()) {
super.onBackPressed();
}
}
it would be much easier if you also gave the stack trace.
However it is possible you are checking the wrong thing for null, change fragments to currentFragment
#Override
public void onBackPressed() {
List fragments = getSupportFragmentManager().getFragments();
BaseExampleFragment currentFragment = (BaseExampleFragment) fragments.get(fragments.size() - 1);
if (currentFragment != null && !currentFragment.onActivityBackPress()) {
super.onBackPressed();
}
}

ViewPager cause crash

I have a viewpager. The viewpager has five fragments. And these fragments have child fragments. When I start my app, it crashes. If I comment out resetMenu() function it works. What is the problem?
HomeActivity.java
#Override
public void onPageSelected(int position) {
listeners[beforePagerPosition].onViewPaused();
tabLayout.getTabAt(beforePagerPosition).getIcon().setAlpha(getResources().getInteger(R.integer.tab_unselected_alpha));
beforePagerPosition = position;
tabLayout.getTabAt(position).getIcon().setAlpha(getResources().getInteger(R.integer.tab_selected_alpha));
listeners[position].onViewResumed();
resetMenu();
hideKeyboard();
}
#Override
public void onPageScrollStateChanged(int state) {
}
private void resetMenu() {
if (getSupportFragmentManager() != null) {
ParentFragment parentFragment = (ParentFragment) listeners[viewPager.getCurrentItem()];
FragmentManager fm = parentFragment.getChildFragmentManager();
if (fm != null && fm.getBackStackEntryCount() > 0) {
FragmentManager.BackStackEntry backStackEntry = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1);
String str = backStackEntry.getName();
BaseMenuFragment fragment = (BaseMenuFragment) fm.findFragmentByTag(str);
fragment.setHasOptionsMenu(true);
}
}
}
OK. I found answer. I added control for ParentFragment isAdded().
ParentFragment parentFragment = (ParentFragment) listeners[viewPager.getCurrentItem()];
if(parentFragment.isAdded()){
....
}

Fragments keep duplicating

Hee Guys,
I'm currently working with fragments and I'm trying to manage it so that when you click twice on the same menu item it won't put 2 of the same fragments on top of eachother. However it still does. Could anyone tell me what I'm doing wrong?
/*
* Method to check which action is behind the selected Menu item. Then call ShowFragment()
* With the correct fragment parameter used with this Menu action value.
*/
public void getAction(int position, Cursor cursor) {
// TODO Auto-generated method stub
mCursor = cursor;
cursor.moveToPosition(position);
String action = cursor.getString(cursor.getColumnIndex(AppMenu.ACTION));
if (action != null) {
if (action.equalsIgnoreCase("home")) {
trans = manager.beginTransaction();
BaseFragment newFragment = new HomeFragment();
if (manager.findFragmentByTag(newFragment.getTag()) != null) {
mCursor.moveToPosition(position);
// Set the current fragment
mCurrentFragment = newFragment;
Bundle bundle = new Bundle();
int fragId = mCursor.getInt(mCursor.getColumnIndex(AppMenu._ID));
Log.i(TAG, fragId + " ");
bundle.putInt("fragmentID", fragId);
newFragment.setArguments(bundle);
trans.replace(R.id.fragmentContainer, newFragment).addToBackStack(
newFragment.tag());
trans.commit();
} else {
trans.show(newFragment);
}
} else if (action.equalsIgnoreCase("event")) {
showFragment(new EventsFragment(), position);
} else if (action.equalsIgnoreCase("location")) {
showFragment(new LocationsFragment(), position);
} else if (action.equalsIgnoreCase("news")) {
showFragment(new NewsFragment(), position);
} else if (action.equalsIgnoreCase("bars")) {
showFragment(new BarsFragment(), position);
} else if (action.equalsIgnoreCase("currency")) {
showFragment(new CurrencyFragment(), position);
} else if (action.equalsIgnoreCase("map")) {
showFragment(new MapFragment(), position);
}
} else {
Log.i(TAG, "You've got a nullpointerexception on getAction().");
}
}
/*
* Method that's called when changing from fragment through Menu or HomeMenu.
*/
public void showFragment(BaseFragment newFragment, int position) {
trans = manager.beginTransaction();
if (manager.findFragmentByTag(newFragment.tag()) == null) {
mCursor.moveToPosition(position);
// Set the current fragment
mCurrentFragment = newFragment;
// Go on and set the bundle values and pass it on the fragment.
Bundle bundle = new Bundle();
int fragId = mCursor.getInt(mCursor.getColumnIndex(AppMenu._ID));
Log.i(TAG, fragId + " ");
bundle.putInt("fragmentID", fragId);
newFragment.setArguments(bundle);
trans.replace(R.id.fragmentContainer, newFragment).addToBackStack(
newFragment.tag());
trans.commit();
} else {
trans.show(newFragment);
}
}
And here are 2 callbacks for when something changes or when back pressed.
/*
* Interface method called whenever a new fragment is created.
*/
#Override
public void onNewFragment(BaseFragment newFragment) {
// TODO Auto-generated method stub
FragmentManager fm = getSupportFragmentManager();
Class<? extends Fragment> newFragmentClass = newFragment.getClass();
if (newFragmentClass == EventsFragment.class
|| newFragmentClass == LocationsFragment.class
|| newFragmentClass == MapFragment.class
|| newFragmentClass == NewsFragment.class
|| newFragmentClass == CurrencyFragment.class
|| newFragmentClass == BarsFragment.class) {
for (Fragment fragment : fm.getFragments()) {
if (fragment != null && ((Object) fragment).getClass() == newFragmentClass) {
while (((Object) mCurrentFragment).getClass() != newFragmentClass) {
popFragment();
}
popFragment();
break;
}
}
}
}
/*
* Interface method called when you navigate back from a fragment.
* Checks which fragment is active, calls upon this fragments back function to clear any data,
* then pops the first fragment on the backstack.
*/
#Override
public void onBackNavigated() {
// TODO Auto-generated method stub
if ((mCurrentFragment instanceof HomeFragment)
&& !((HomeFragment) mCurrentFragment)
.isStackEmpty()) {
System.exit(0);
// break;
}
if ((mCurrentFragment instanceof LocationsFragment)
&& !((LocationsFragment) mCurrentFragment)
.isStackEmpty()) {
((LocationsFragment) mCurrentFragment).goBack();
// return;
}
if ((mCurrentFragment instanceof EventsFragment)
&& !((EventsFragment) mCurrentFragment)
.isStackEmpty()) {
((EventsFragment) mCurrentFragment).goBack();
// return;
}
if ((mCurrentFragment instanceof MapFragment)
&& !((MapFragment) mCurrentFragment).isStackEmpty()) {
((MapFragment) mCurrentFragment).goBack();
// break;
}
if ((mCurrentFragment instanceof BarsFragment)
&& !((BarsFragment) mCurrentFragment).isStackEmpty()) {
((BarsFragment) mCurrentFragment).goBack();
// break;
}
if ((mCurrentFragment instanceof CurrencyFragment)
&& !((CurrencyFragment) mCurrentFragment).isStackEmpty()) {
((CurrencyFragment) mCurrentFragment).goBack();
// break;
}
popFragment();
}
/*
* Pops the first fragment in the backstack. Then sets this as the new current fragment.
* If no fragment is in the backstack then finish() is called. Which will destroy the only fragment.
* Which in this case exits the application.
*/
public void popFragment() {
if (manager.getBackStackEntryCount() > 1) {
manager.popBackStack();
manager.executePendingTransactions();
ArrayList<Fragment> reversedFragments = new ArrayList<Fragment>(
manager.getFragments());
Collections.reverse(reversedFragments);
for (Fragment fragment : reversedFragments)
if (fragment != null) {
mCurrentFragment = (BaseFragment) fragment;
break;
}
} else {
finish();
}
}
**NOTE : ** The tag() functions calls a final String from the fragment itself with the same hardcoded tag everytime. So every fragment of the same class has the same tag. (Which should prevent double fragments, but it still doesn't)
Solution:
The tag() was returning null al the time. (Don't know why) So I changed the showFragment(fragment, tag, position) and hardcoded the tag in the mainactivity. Then used :
trans.replace(R.id.fragmentContainer, newFragment, tag);
//instead of
trans.replace(R.id.fragmentContainer, newFragment).addToStackBack(tag);
Don't forget to still add it to the backstack! Or else your back navigation won't work.
Just add an extra line: trans.addToBackStack(tag);
You can set the tag while adding/replacing the Fragment,
So you need to mention it as :
trans.replace(R.id.fragmentContainer, newFragment,tag);
Pass the tag value to the method according to the Fragment
showFragment(new EventsFragment(),tag, position);
Hope it will help you ツ

Android : Return to previous fragment on back press

I have implemented Navigation Drawer which is a subclass of Activity. I have many fragments in my application. My question goes here
Imagine there are 3 fragments :
Fragment_1 : Fragment_2 : Fragment_3
When I start my application, Fragment_1 is loaded
When I click on some components on Fragment_1, I'm navigated to Fragment_2 and so on..
So it's like
Fragment_1 > Fragment_2 > Fragment_3
When I press back key from Fragment_2, I'm navigated back to Fragment_1
But when I press back key from Fragment_3, I'm navigated back to Fragment_1 (instead of Fragment_2)
I want something like this in my application on Back Key press
Fragment_1 < Fragment_2 < Fragment_3
I have used Fragment, FragmentManager, FragmentTransaction as follows :
MyFragment fragment = new MyFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null)commit();
and I tried overriding onBackPressed() in my MainActivity :
#Override
public void onBackPressed() {
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0)
super.onBackPressed();
}
Update your Activity#onBackPressed() method to:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
The reason your implementation doesn't work is because the method FragmentManager#popBackStack() is asynchronous and does not happen right after it is called.
From the documentation:
This function is asynchronous -- it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.
Reference: http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack(java.lang.String,%20int)
You have to implement your own backstack implementation as explained here
Separate Back Stack for each tab in Android using Fragments
You can call the popFragments() whenever you click the back button in a fragment and call pushFragments() whenever you navigate from one Fragment to other.
in Short,
public void onBackPressed()
{
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.popBackStack();
}
The tric is in FragmentManager#executePendingTransactions();.
This is what I use for nested fragments as well...:
/**
* if there is a fragment and the back stack of this fragment is not empty,
* then emulate 'onBackPressed' behaviour, because in default, it is not working.
*
* #param fm the fragment manager to which we will try to dispatch the back pressed event.
* #return {#code true} if the onBackPressed event was consumed by a child fragment, otherwise
*/
public static boolean dispatchOnBackPressedToFragments(FragmentManager fm) {
List<Fragment> fragments = fm.getFragments();
boolean result;
if (fragments != null && !fragments.isEmpty()) {
for (Fragment frag : fragments) {
if (frag != null && frag.isAdded() && frag.getChildFragmentManager() != null) {
// go to the next level of child fragments.
result = dispatchOnBackPressedToFragments(frag.getChildFragmentManager());
if (result) return true;
}
}
}
// if the back stack is not empty then we pop the last transaction.
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
fm.executePendingTransactions();
return true;
}
return false;
}
and in my onBackPressed :
if (!FragmentUtils.dispatchOnBackPressedToFragments(fm)) {
// if no child fragment consumed the onBackPressed event,
// we execute the default behaviour.
super.onBackPressed();
}
Use this code on tab change in your main activity to clear the stack.
int count = getFragmentManager().getBackStackEntryCount();
if(count>0){
for (int i = 0; i <count; i++) {
getFragmentManager().popBackStack();
}
}
Then on Back pressed of your main activity do this
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onbackpressed();
}
else {
getFragmentManager().popBackStack();
}
}
Here is working and tested code by me, This will help you
private static final int TIME_INTERVAL = 2000;
private long mBackPressed;
private void applyExit() {
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
finish();
} else {
Toast.makeText(this,"Press Again to exit",Toast.LENGTH_LONG).show();
}
mBackPressed = System.currentTimeMillis();
}
#Override
public void onBackPressed() {
fm = getSupportFragmentManager();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
if (fm.getFragments().size() <= 1) {
applyExit();
} else {
for (Fragment frag : fm.getFragments()) {
if (frag == null) {
applyExit();
return;
}
if (frag.isVisible()) {
FragmentManager childFm = frag.getChildFragmentManager();
if (childFm.getFragments() == null) {
super.onBackPressed();
return;
}
if (childFm.getBackStackEntryCount() > 0) {
childFm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
return;
} else {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
return;
}
}
}
}
}

Categories

Resources