How to control fragment onResume? - android

I have three fragments A、B、C , my process is A to B to C .
I want that when i change to C and call back to B , B can switch to A immediately.
So i set the switch fragment function on onResume on B .
But the result is that i always land up on A fragment , because when i change to B the function onResume be called
I know i can remove transaction.addToBackStack(null); then i can C to A
, but it will cause some bug in my project , so i try to keep it.
Is any function only start when C call back to B ?
Thanks in advance.
Below is my switch function:
private void switchFragment(Fragment fragment) {
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.mainFrame, fragment, null);
transaction.addToBackStack(null);
transaction.commit();
}
I try to add onResume on fragment B , but it will be A to B , and then B go back to A immediately.
#Override
public void onResume() {
super.onResume();
//go back to fragment A
switchFragment(NewHomepage.newInstance());
}

your fragment transition code should be:
private void switchFragment(Fragment fragment) {
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.mainFrame, fragment, null);
transaction.addToBackStack("fragment_name_tagX");
transaction.commit();
}
above, X is your fragment. After you navigate from fragment A to C using above function, your stack will have every fragment with name 'fragment_name_tag' that you assign.
#Override
public void onBackPressed() {
FragmentManager fm = getActivity().getSupportFragmentManager();
int count = fm.getBackStackEntryCount();
if (count != 0) {
fm.popBackStack ("fragment_name_tagB",FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
super.onBackPressed();
}
}
So when you now press back button from fragment C, it will go on fragment A.

Related

Remove fragment issue

I have three fragments :
A is my main fragment, B is a login fragment, successful login will enter C fragment.
When I click on back button, I need to move to Fragment A from Fragment C.
My issue is that, when I click on back button I still move on Fragment B from Fragment A.
How can I fix my issue?
Here is my switch fragment function:
public void switchFragment(Fragment fragment) {
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.mainFrame, fragment, null);
transaction.addToBackStack(null);
transaction.commit();
}
A fragment(NewHomepage) to B(LoginFragment) fragment:
switchFragment(LogInFragment.newInstance());
This is my B fragment, it has the value logged to decide switch A fragment or not when it come from C fragment.
I think that issue must be here, when go back to A fragment and click back button want to quit the APP, I can see the logcat show 1=> and 2=> .
String logged = memberData.getUD_MBTYPENAME(); //get the value when login succeed
Log.d(TAG,"1=>"+logged);
//If UD_MBTYPENAME is not null,change to A fragment
if (!TextUtils.isEmpty(logged)) {
Log.d(TAG,"2=>"+logged);
((MainActivity) getActivity()).switchFragment(NewHomepage.newInstance());
}
Here is about my MainActivity about onKeyDown and switchFragment:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
quickDialog();//It's a alert dialog
return false;
}
}
return super.onKeyDown(keyCode, event);
}
public void switchFragment(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.mainFrame, fragment, null);
transaction.addToBackStack(null);
transaction.commit();
}
Take a reference change the code like this , if I don't use transaction.addToBackStack(null); , the issue is still there , even though remove transaction.addToBackStack(null);
When I back to A , I have to click twice back to show the alert dialog, I don't know what happened when I click back first time in A fragment.
if (!TextUtils.isEmpty(logged)){
Log.d(TAG,"2=>"+logged);
hideFragment(LogInFragment.newInstance());
switchFragment(NewHomepage.newInstance());
}
public void switchFragment(Fragment fragment) {
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.mainFrame, fragment, null);
//remove it will fix my issue , but I have to click back twice to show alert dialog , I don't know what happened click it first time in A fragment.
//transaction.addToBackStack(null);
transaction.commit();
}
public void hideFragment(Fragment fragment) {
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.hide(fragment);
transaction.commit();
}
remove hideFragment and use manager.popBackStack(); on switchFragment , the issue will be fixed.
Try
It will show fragment if it is already added.
Use fragmentTransaction.show method to re-use existing fragment i.e. saved instance.
public void switchFragment (Fragment oldFragment, Fragment newFragment, int frameId) {
boolean addFragment = true;
FragmentManager fragmentManager = getFragmentManager ();
String tag = newFragment.getArguments ().getString ("TAG");
Fragment fragment = fragmentManager.findFragmentByTag (tag);
// Check if fragment is already added
if (fragment != null && fragment.isAdded ()) {
addFragment = false;
}
// Hide previous fragment
String oldFragmentTag = oldFragment.getArguments ().getString (BaseFragment.TAG);
if (!tag.equals (oldFragmentTag)) {
FragmentTransaction hideTransaction = fragmentManager.beginTransaction ();
Fragment fragment1 = fragmentManager.findFragmentByTag (oldFragmentTag);
hideTransaction.hide (fragment1);
hideTransaction.commit ();
}
// Add new fragment and show it
FragmentTransaction addTransaction = fragmentManager.beginTransaction ();
if (addFragment) {
addTransaction.add (frameId, newFragment, tag);
addTransaction.addToBackStack (tag);
}
else {
newFragment = fragmentManager.findFragmentByTag (tag);
}
addTransaction.show (newFragment);
addTransaction.commit ();
}

Android fragment handling back button

I am creating an application with multiple fragments. I have four fragments fragment1, fragment2, fragment3, fragment4. I am moving from different orders like f1 -> f2 -> f4 -> f3 -> f1 or any other order. But when I click the back button from each fragment I need to go to the previous fragment. How to handle this.
Edit 1:
I already tried
FragmentManager fm = ((Activity) context).getFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); i++) {
fm.popBackStack();
}
Which is not help me to solve my issue.
Sample code of Manage Fragment back stack
private Stack<Fragment> stack = new Stack<Fragment>();
public void pushFragments(Fragment fragment, boolean shouldAnimate,
boolean shouldAdd) {
drawerClose = false;
if (shouldAdd)
stack.push(fragment);
this.changeFragment = fragment;
invalidateOptionsMenu();
changeFragment(fragment, shouldAnimate, false);
}
public void popFragments() {
/*
* Select the second last fragment in current tab's stack.. which will
* be shown after the fragment transaction given below
*/
Fragment fragment = stack.elementAt(stack.size() - 2);
// / pop current fragment from stack.. /
stack.pop();
/*
* We have the target fragment in hand.. Just show it.. Show a standard
* navigation animation
*/
this.changeFragment = fragment;
invalidateOptionsMenu();
changeFragment(fragment, false, true);
}
private void changeFragment(Fragment fragment, boolean shouldAnimate, boolean popAnimate) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (shouldAnimate)
ft.setCustomAnimations(R.anim.slide_in_right,
R.anim.slide_out_left);
if (popAnimate)
ft.setCustomAnimations(R.anim.slide_in_left,
R.anim.slide_out_right);
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
//On BackPress just check this thing
private void backManage() {
if (stack.size() > 1) {
popFragments();
}
}
Use addToBackStack(String tag), while committing the fragment to add the fragment into the stack of your application:
getFragmentManager().beginTransaction().replace(fragmentContainer.getID(), fragment)
.addToBackStack(null).commit();`
on Activity
#Override
public void onBackPressed() {
if(check_if_backstack_is_null)
super.onBackPressed();
else
{
popupFromBackstack();
}
}
You should override onBackPressed method:
#Override
public void onBackPressed() {
if (fragment != null && fragment.getChildFragmentManager().getBackStackEntryCount() > 0){
fragment.getChildFragmentManager().popBackStack();
}else {
super.onBackPressed();
}
}
For this you can set addToBackStack to fragment transation and then call commit.
By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.
If you add multiple changes to the transaction (such as another add() or remove()) and call addToBackStack(), then all changes applied before you call commit() are added to the back stack as a single transaction and the Back button will reverse them all together.
You just need to add addToBackStack(null) by FragmentTransaction.
when you are calling next Fragment just add this method with null parameter.
Like this.
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(..............);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Use this lines of code for it:-
#Override
public void onBackPressed() {
if ( getSupportFragmentManager().getBackStackEntryCount() > 0){
fm.popBackStack();
}else {
super.onBackPressed();
}
}
To get the backStack functionality in your fragmentthan you should have use the .addToBackStack(null) , while performing the fragment transaction like below:-
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.YOUR_CONTAINER, YOUR_FRAGMENT,"TAG")
.addToBackStack(null) /// IT IS NECESSARY TO GET THE BACK STACK PROPERTY IN YOUR FRAGMENT
.commitAllowingStateLoss();

Is there anyway to swap or reorder fragment BackStack entry?

am creating multiple fragment app, which require easy changing of fragment tabs, whose BackStack entry must be kept. On user click fragment must be pop up immediate. I think reordering BackStack is the best option. Do anyone know how to reorder BackStack ?
I have 5 fragments A,B,C,D,E. if user open fragment like A ---> B ---> C ---> D ---> E . using default back stack,back key it works fine. But when user opens A ---> B ---> C ---> D ---> E ---> B. After this if user click back, default back stack will goes to A.
There is no api for this usecase, but there are other means to do so:
Example
FragmentBackStackModifyActivity
use non-swipable viewpager and on addOnPageChangeListener create arraylist and save all pages that opened. onBackPressed will compare arraylist and show pages.
The user follows the path A ---> B ---> C ---> D ---> E then he wants to come to B. So what you should do is:
check if B is already in the back stack or not.
If it is there, then popBackStackImmediate to return to B
If it is not there, then add the fragment B normally.
So replace fragment should be something like this:
public void replaceFragment(Fragment fragment) {
String fragmentTag = fragment.getClass().getCanonicalName(); //unique name for the fragment, which will be used as tag.
FragmentManager fragmentManager = getSupportFragmentManager();
boolean isPopped = fragmentManager.popBackStackImmediate(fragmentTag, 0); // trying to return to the previous state of B if it exists.
if (!isPopped && fragmentManager.findFragmentByTag(fragmentTag) == null){ // fragment is not in the backstack, so create it.
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.frame_layout, fragment, fragmentTag);
ft.addToBackStack(fragmentTag);
ft.commit();
}
}
Remember, this will return to the previous state of B.
TIP: Since you don't want two instances of any fragment, So try to create a singleton instance of them. Because, if you are creating a new instance of the fragment and that fragment already exists in the back stack then the new instance will be ignored (because you are returning to the previous state).
You Can Try this...
onBackpressed
#Override
public void onBackPressed() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.frame_container);
if (f instanceof FragmentE)
{
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-1).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else if (f instanceof FragmentD) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-2).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
else if (f instanceof FragmentC) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-3).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
else if (f instanceof FragmentB) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-4).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
else
{
super.onBackPressed();
}
}
for back remove stack
final android.app.FragmentManager fm = getFragmentManager();
fm.addOnBackStackChangedListener(new android.app.FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() ==0) {
// dLayout.closeDrawers();
finish();
}
else
{
// dLayout.closeDrawers();
}
}
});
May be call addToBackstack() only when the fragment is not added before
Suppose as in your case when user is in Fragment E and when user calls Fragment B check if the Fragment B is already added in back stack
if yes, Then dont call addToBackstack for that FragmentTransaction.
else ,call addToBackstack()
check my sample code:
private void addFragment (Fragment fragment){
boolean isFragment=false;
String backStateName = fragment.getClass().getName();
FragmentManager fm = getFragmentManager();
for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
Log.i(TAG, "Found fragment: " + fm.getBackStackEntryAt(entry).getId());
if(fm.getBackStackEntryAt(entry).getId().equalsIgnoreCase(FragmentB))// check if fragment is in back stack
{
isFragment=true;
}
}
if (!isFragment){ //fragment added to back stack, create it.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, FragmentB).addToBackStack(FragmentB).commit();
}else {//else dont call addToBackStack()
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, FragmentB).commit();
}
}
Just place this code in your MainActivity
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
//super.onBackPressed();
if (getFragmentManager().getBackStackEntryCount() == 1) {
finish();
}
getFragmentManager().popBackStack();
}
}
Here getFragmentManager().getBackStackEntryCount() == 0 will checks that whether the stack entry is at 0 or not, if it's on 0 then the Activity will be finished.
In your case A --> B --> C --> D --> E --> B
A will be on 0,
B will be on 1,
C on 2,
D on 3,
E on 4,
B on 5
So when you click on back, the if condition will checks that the backstack count is on 0.

android fragment handle back button press not working

I am working fragment, I replaced FragmentA by fragment B.it's working perfect,but when I press back button I can't back Fragment A.
I tried to override onKeyDown method,but I can't override this method in fragment
this is a my source
CategoryViewPager fragment1 = new CategoryViewPager();
FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction().addToBackStack("method");
ft.setCustomAnimations(R.anim.trans_left_in, R.anim.trans_left_out);
ft.replace(R.id.content_frame, fragment1, "fragment2");
ft.commit();
when I use CategoryViewPager and click back button I can't go back(fragment wich i replaced this fragment)
how can I solve my problem?
Call addToBackStack() before you commit the transaction:
getSupportFragmentManager().beginTransaction()
// Add this transaction to the back stack
.addToBackStack()
.commit();
No need to use tag in your case. just use like this
/*
* Add this transaction to the back stack.
* This means that the transaction will be remembered after it is
* committed, and will reverse its operation when later popped off
* the stack.
*/
fragmentTransaction.addToBackStack(null);
It is better to handle back button press through your activity unless your actvity host large number of fragments.When you press back button inside your fragment onBackPressed() method of your activity will be called which can be overridden and handled..So handling back button for fragments can be done in this way..
MainActvity
public static boolean isMainActivityShown ;
public static boolean isFragment1Shown=false ;
public static boolean isFragment2Shown=false ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isMainActivityShown=true //inside onCreate method put isMainActivityShown true
.
.
.
}
.
.
Fragment currentFragment = new Fragment1();
isMainActivityShown=false; //when moving to fragment1
isFragment1Shown=true;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
.commit();
#Override
public void onBackPressed() {
if(isMainActivityShown)
{
finish();
}
else if(isFragment1Shown)
{
//write the code to handle back button when you are in Fragment1
}
else if(isFragment2Shown)
{ //When you are in Fragment 2 pressing back button will move to fragment1
Fragment currentFragment = new Fragment1();
isFragment2Shown=false;
isFragment1Shown=true;
FragmentManager frgManager;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
.commit();
}
}
Fragment1
Fragment currentFragment = new Fragment2();
MainActivity.isFragment1Shown=false;
MainActivity.isFragment2Shown=true;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
.commit();
Check this link
Check the addToBackStack(String name) method. This should solve your problem.

Android: Fragments backStack

Im trying to load an new fragment when a method is called. This method creates a new fragment and "replaces" the other fragment:
private void showTestFragment(Fragment oldFragment, boolean addBackStack, BaseAdapter adapter, int position) {
Cursor cursor = (Cursor)adapter.getItem(position);
if(cursor != null){
int idx = cursor.getColumnIndexOrThrow(Episode._ID);
long rowId = cursor.getLong(idx);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(oldFragment != null){
Log.i(TAG, "Removing the old fragment");
fragmentTransaction.remove(oldFragment);
}
TestFragment testFragment = new TestFragment();
testFragment.setId(rowId);
fragmentTransaction.add(android.R.id.content, testFragment);
if(addBackStack){
Log.i(TAG, "Added to the backstack");
fragmentTransaction.addToBackStack(TAG);
}
fragmentTransaction.commit();
Fragment f = getFragmentManager()
.findFragmentById(R.id.index);
Log.i(TAG, "after commit, frag is "+ f);
}
}
This works fine, until i go back. The last fragment, should be removed when i go back. Before i'm going to implement methods on the activities
public void onBackPressed(){}
to remove the last fragment, i want to know if i handle the fragment change correctly. It looks like i'm missing something here..
If you really want to replace the fragment then use replace() methode instead of doing a remove() and an add().
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(..............);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Don't forget to do the addToBackStack(null) so your previous state will be added to the backstack allowing you to go back with the back button.
See also https://developer.android.com/reference/android/app/FragmentTransaction.html#replace(int, android.app.Fragment, java.lang.String) .
Another good source is http://developer.android.com/guide/components/fragments.html (search for replace() function).
Just remove first and the call super.onBackPressed
public void onBackPressed(){
// here remove code for your last fragment
super.onBackPressed();
}
//lets wait for systems back to finish
super.onBackPressed();
//here we believe a fragment was popped, so we need to remove the fragment from ourbackstack
if(fragmentBackStack.size()>0)
{
Log.d("custombackstack","before back: "+fragmentBackStack.size()+" current:"+fragmentBackStack.peek());
fragmentBackStack.pop();
}
//after popping is the size > 0, if so we set current fragment from the top of stack, otherwise we default to home fragment.
if(fragmentBackStack.size()>0)
{
Log.d("custombackstack","after back: "+fragmentBackStack.peek());
currentFragment = fragmentBackStack.peek();
}
else
{
//back stack empty
currentFragment = HOME_FRAGMENT;
}

Categories

Resources