Android backstack functioning for fragments - android

I have written a code where I try to navigate in between fragments 1, 2 ,3 ,4. The navigation is like: 1->2->3->4->2.
Each fragment has a button whose onClickListener calls the method in interface which is implemented by the mainactivity, wherein position is passed as parameter.
e.g. onClick on the button in 4th fragment calls the method wherein I pass the position parameter as '2' to call the second fragment.
Now, I have added the transaction 1->2 to the backstack, Using a backstack name "second". When, I try to go from 4>2, I use the function popBackStackImmediate("second", 0). But, the boolean response is false and nothing is popped from the stack.
My questions are :
Why is popBackStackImmediate returning false?
What is the use of second parameter in the same function i.e flag ?
When we add the transaction in the backstack, the transaction is saved and not the fragment. So, where is the fragment object getting saved actually as the backstack saves the transaction?
The MainActivity in my code is :
`
public class MainActivity extends AppCompatActivity implements Frag1.OnFragmentInteractionListener, Frag2.OnFragmentInteractionListener, Frag3.OnFragmentInteractionListener, Frag4.OnFragmentInteractionListener {
LinearLayout layout;
Frag1 frag1;
Frag2 frag2;
Frag3 frag3;
Frag4 frag4;
android.support.v4.app.FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("I", "Main Act");
layout = (LinearLayout) findViewById(R.id.frag);
frag1 = Frag1.newInstance();
transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.add(R.id.frag, frag1, "first");
// frag1 = Frag1.newInstance();
// transaction.add(R.id.frag, frag1, "first1");
// transaction.add(R.id.frag, frag2, "second");
// transaction.add(R.id.frag, frag2, "second");
// transaction.add(R.id.frag, frag3, "third");
// Commit the transaction
// transaction.add(R.id.frag, frag3, "third");
// transaction.replace(R.id.frag, frag2, "second");
transaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Fragment to activity interface implementation
#Override
public void onFragmentInteraction(int pos) {
if (pos == 2) {
// Fragment f = getSupportFragmentManager().findFragmentByTag("second");
FragmentManager manager = getSupportFragmentManager();
boolean isAvail = manager.popBackStackImmediate("second", 0);
if (isAvail) {
// frag2 = (Frag2) f;
Log.i("MainAct", "Instance of 2 yes");
}else{
transaction = getSupportFragmentManager().beginTransaction();
frag2 = Frag2.newInstance();
Log.i("MainAct", "Instance of 2 No");
transaction.replace(R.id.frag, frag2, "second");
transaction.addToBackStack("second");
transaction.commit();
}
} else if (pos == 3) {
Fragment f = getSupportFragmentManager().findFragmentByTag("third");
transaction = getSupportFragmentManager().beginTransaction();
if (f instanceof Frag3) {
frag3 = (Frag3) f;
Log.i("MainAct", "Instance of 3 yes");
}else{
frag3 = Frag3.newInstance();
Log.i("MainAct", "Instance of 3 No");
}
transaction.replace(R.id.frag, frag3, "third");
transaction.commit();
}
else if (pos == 4) {
Fragment f = getSupportFragmentManager().findFragmentByTag("four");
transaction = getSupportFragmentManager().beginTransaction();
if (f instanceof Frag3) {
frag4 = (Frag4) f;
Log.i("MainAct", "Instance of 4 yes");
}else{
frag4 = Frag4.newInstance();
Log.i("MainAct", "Instance of 4 No");
}
transaction.replace(R.id.frag, frag4, "four");
transaction.commit();
}
}
}`

You are trying to call popBackStackImmediate("second", 0); instead replace the fragment.
Try this,
Create Interface PageTraveller and implement in MainActivity
public interface PageTraveller {
public void openPage(int pageNo);
}
override the method openPage()
#Override
public void openPage(int pageNo) {
android.support.v4.app.Fragment fragment;
switch (pageNo){
case 1:
fragment = getSupportFragmentManager().findFragmentByTag("fragmentOne");
fragmentManager.beginTransaction().replace(R.id.pageContainer,fragment).addToBackStack("fragmentOne").commit();
break;
case 2:
fragment = getSupportFragmentManager().findFragmentByTag("fragmentTwo");
if (fragment instanceof FragmentTwo)
fragmentTwo = (FragmentTwo)fragment;
else
fragmentTwo = new FragmentTwo();
fragmentManager.beginTransaction().replace(R.id.pageContainer,fragmentTwo).addToBackStack("fragmentTwo").commit();
break;
case 3:
fragment = getSupportFragmentManager().findFragmentByTag("fragmentThree");
if (fragment instanceof FragmentTwo)
fragmentThree = (FragmentThree)fragment;
else
fragmentThree = new FragmentThree();
fragmentManager.beginTransaction().replace(R.id.pageContainer,fragmentThree).addToBackStack("fragmentThree").commit();
break;
case 4:
fragment = getSupportFragmentManager().findFragmentByTag("fragmentFour");
if (fragment instanceof FragmentTwo)
fragmentFour = (FragmentFour)fragment;
else
fragmentFour = new FragmentFour();
fragmentManager.beginTransaction().replace(R.id.pageContainer,fragmentFour).addToBackStack("fragmentFour").commit();
break;
}
}
Create First fragment FragmentOne
public class FragmentOne extends Fragment{
PageTraveller pageTraveller;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View viewOne = inflater.inflate(R.layout.fragment_one,null);
Button btnOne = (Button)viewOne.findViewById(R.id.text1);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pageTraveller.openPage(2);
}
});
return viewOne;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
pageTraveller = (PageTraveller) context;
}
}
in XML fragment_one add
<Button
android:id="#+id/btnOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:layout_gravity="center|center_horizontal|center_vertical"
android:text="Fragment 1"/>
Create FragmentTwo, FragmentThree, FragmentFour same way as above.
but in your FragmentFour call pageTraveller.openPage(2);
For more reference try 1. go back to the previous fragment in the backstack
Fragments official Android Developer website
Its work for me, try it may help you.

Related

BackStack not navigating to the correct Fragment

Hello im trying to navigate between some fragments with addToBaackStack but having issues with it ,
Ok i will explain it in detail so there should be no confusuion
1 :- I have only one activity (main activity) which consist of all the other fragments and a fragment container to hold the fragments in it , i have implemented bottom navigation in the main activity ,where the bottom navigation have 5 main fragments home,following,upload,notification and profile my issues is related to the profile fragment
2 :- In the profile fragment i have some buttons like edit profile button which opens edit profile fragment but now when i presse back it should navigate back to the profile fragment which it is not doing ,its is navigating to the last fragment of the bottomnavigation (which can be any other of the main fragments for eg if my last fragment is following fragment then when i press back from the edit profile fragment it goes to the following fragment )but this not happens if i put a back arrow icon in edit profile fragment then when i click the back arrow it perfectly navigate me to the profile fragments as it is not related to addToBackStack
It shows that the issue is related with my bottom navigation but i dont know how to exactly fix it
Prifile_Fragment.java
editProfileButton.setOnClickListener(v -> {
Fragment edit_profile = new Edit_Profile();
assert getFragmentManager() != null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, edit_profile);
transaction.addToBackStack(null);
transaction.commit();
});
MainActivity.java // where the bottom navigation is implemented
public class MainActivity extends AppCompatActivity {
public BottomNavigationView bottomNavigationView;
Deque<Integer> integerDeque = new ArrayDeque<>(4);
boolean flag = true;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setContentView(R.layout.activity_main);
Window window = this.getWindow();
window.setStatusBarColor(this.getResources().getColor(R.color.black));
bottomNavigationView = findViewById(R.id.bottom_navigation_view);
integerDeque.push(R.id.nav_home);
loadFragments(new Home_Fragment());
bottomNavigationView.setSelectedItemId(R.id.nav_home);
bottomNavigationView.setOnNavigationItemSelectedListener(
item -> {
int id = item.getItemId();
if (integerDeque.contains(id)) {
if (id == R.id.nav_home) {
integerDeque.size();
if (flag) {
integerDeque.addFirst(R.id.nav_home);
flag = false;
}
}
integerDeque.remove(id);
}
integerDeque.push(id);
loadFragments(getFragment(item.getItemId()));
return false;
}
);
}
#SuppressLint("NonConstantResourceId")
private Fragment getFragment(int itemId) {
switch (itemId) {
case R.id.nav_home:
bottomNavigationView.getMenu().getItem(0).setChecked(true);
return new Home_Fragment();
case R.id.nav_following:
bottomNavigationView.getMenu().getItem(1).setChecked(true);
return new Following_Fragment();
case R.id.nav_upload:
bottomNavigationView.getMenu().getItem(2).setChecked(true);
return new Upload_Fragment();
case R.id.nav_notification:
bottomNavigationView.getMenu().getItem(3).setChecked(true);
return new Notification_Fragment();
case R.id.nav_profile:
bottomNavigationView.getMenu().getItem(4).setChecked(true);
return new Profile_Fragment();
}
bottomNavigationView.getMenu().getItem(0).setChecked(true);
return new Home_Fragment();
}
public void loadFragments(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName())
.commit();
}
}
#Override
public void onBackPressed() {
integerDeque.pop();
if (!integerDeque.isEmpty()) {
loadFragments(getFragment(integerDeque.peek()));
} else {
finish();
}
}
}
Have you consider to use popBackStack ? You can try this.
#Override
public void onBackPressed() {
final FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
} else {
finish();
}
}

Adding back button to fragment

I have a bottom navigation bar that contains 4 fragments and when a tab is selected a new instance of that fragment is loaded.
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = HomeFragment.newInstance();
break;
case R.id.navigation_cards:
fragment = CardsFragment.newInstance();
break;
case R.id.navigation_deals:
fragment = DealsFragment.newInstance();
break;
case R.id.navigation_settings:
fragment = SettingsFragment.newInstance();
break;
}
if (fragment != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content, fragment);
fragmentTransaction.commit();
}
return true;
}
};
Now in my HomeFragment there is a RecyclerView that On Item Select it opens a new Fragment:
myViewHolder.cardView.setOnClickListener(view -> {
System.out.println("clicked");
Fragment fragment = new TargetDetailsFragment();
FragmentTransaction ft = ((AppCompatActivity) context).getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.content, fragment).addToBackStack(null);
ft.commit();
});
I want to add a back button to the TargetDetails Fragments that takes you back to the home page when selected and I attempted doing that by implementing OnBackStackChangedListener in the Main activity
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}
#Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
getSupportFragmentManager().popBackStack();
return true;
}
}
but the problem is when I click on it its reloads the HomeFragment Again but I simply want it to go back to the saved instance of that Fragment
Here is my code that I have used for the ViewPager, the idea is to see if the current page number is 0 than to proceed super.onBackPressed(); otherwise go to the previous fragment:
#Override
public void onBackPressed() {
if(vpPager.getCurrentItem()!=0) {
vpPager.setCurrentItem(vpPager.getCurrentItem()-1, true);
} else {
super.onBackPressed();
}
}
By adding below code in your Activity.
The fragment back stack can be managed.
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
Hello #Bolu Okunaiya i think you should try this it will help you to manage backstack to desired fragment without loading same fragment again.
For Stop loading previous fragment you should use "add" instead of "replace" with your FragmentTransaction
Inside your MainActivity
#Override
public void onBackStackChanged() {
//shouldDisplayHomeUp();
Fragment currentFragment = getActivity().getFragmentManager()
.findFragmentById(R.id.fragment_container);
if (currentFragment instanceof TargetDetails) {
Log.v(TAG, "your current fragment is TargetDetails");
popBackStackImmediate(); //<<<< immediate parent fragment will open,which is your HomeFragement
}
}
To use popBackStackImmediate() you need to *replace FragmentA with FragmentB and use addToBackstack() before commit().

Backstack android fragment navigation

This is how I used navigation drawer to display Fragments:
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Fragment0();
break;
case 1:
fragment = new Fragment1();
break;
case 2:
fragment = new Fragment2();
break;
case 3:
fragment = new Fragment3();
break;
case 4:
fragment = new Fragment4();
break;
case 5:
fragment = new Fragment5();
}
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment)
.addToBackStack(null)
.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(drawerll);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
Suppose if the user navigates to Fragment 2-> Fragment 5-> Fragment3.
If the user clicks the back button I need to have the descending order and on each fragment I am displaying the name of the Fragment when he goes to that particular fragment ie:
Fragment 3-> Fragment 5-> Fragment2.
This is what I have tried:
First Method:
FragmentManager fm = getSupportFragmentManager();
int count = fm.getBackStackEntryCount();
for(int i = 0; i < count; ++i) {
fm.popBackStackImmediate();
}
Second Method:
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
I'm unable to get this working**(ie.. I'm unable to move it back to the fragment where I have come from**) and unable to display the name of the fragment based on the backstack
Any help is greatly appreciated.
Your navigation is working fine I guess and the issue you are facing is the tittle for which you can use
public class SampleFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle("Screen name");
return v;
}
}
in every fragment. And whenever you backpress the onCreateView method of fragmemt(the one which is poping from the backstack) gets called and the tittle will again set replacing the old tittle.
1. Handle back
You can use getSupportFragmentManager().popBackStack() method in onBackPressed:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
getSupportFragmentManager().beginTransaction().commit();
}
else {
super.onBackPressed();
}
}
Don't forget to add the fragment in BackStack like :
transaction.addToBackStack(null);
2. Display Name
To show the current fragment name in actionbar, you can get it on onResume of your Fragment :
#Override
protected void onResume() {
super.onResume();
((FrgmentActivtiyName)getActivity).changeTitle("title");
}
Define a method which set the title in the actionbar in your FrgmentActivity:
public void changeTitle(String titleToSet) {
// set title as titleToSet
}
Hope it helps ツ
Please try this:
In the activity which holds the fragments, override the onbackPressed() method by,
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
getSupportFragmentManager().beginTransaction().commit();
}
else {
super.onBackPressed();
}
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
menuList.setItemChecked(position, true);
menuList.setSelection(position);
}

Handling fragment back stack with Navigation Drawer

I am implementing navigation drawer and works well. So i am calling fragment on navigation drawer click and it is also working and further more i am calling another fragment from Home page fragment and maintain the back stack for every fragment but the problem is back press from the child fragment i can't go to Home page fragment and just exited from application. I don't want this. What i want Click on
Navigation Drawer->HomePageFragment->AnotherChild Fragment(On List Item click of HomePageFragment)
but on back pressed without going to Homepage fragment its directly exit with application. Here is my code: (In Fragment Activity with Navigation Drawer)
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ScheduleFragment();
break;
case 1:
fragment = new Result_Fragment();
break;
case 2:
fragment = new Live_Match_Fragment();
break;
case 3:
// fragment = new Live_Match_Fragment();
break;
case 4:
fragment = new Team_Fragment();
break;
default:
break;
}
if (fragment != null) {
fragmentManager = getFragmentManager();
fragmentManager.popBackStackImmediate("0", 0);
int count = fragmentManager.getBackStackEntryCount();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(String.valueOf(count)).commit();
Log.e("Count in Activiy", ""+count);
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
Now in BackPressed() in FragmentActivity.
#Override
public void onBackPressed() {
if (fragmentManager.getBackStackEntryCount() <= 1) {
finish();
return;
}
super.onBackPressed();
}
Now calling another child fragment from HomePage fragment on Listview item click.
team_lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TeamDetailFragment myDetailFragment = new TeamDetailFragment();
FragmentManager fragmentManager = getFragmentManager();
int count = fragmentManager.getBackStackEntryCount();
Log.e("Count in Fragment", "" + count);
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction
.replace(R.id.frame_container, myDetailFragment)
.setTransition(
FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(String.valueOf(count)).commit();
}
});
So anybody knows then help me. Help will be appreciate.
There is an issue with nested fragments in android
https://code.google.com/p/android/issues/detail?id=40323
Android doesn't handle back press well if transactions were in nested fragments.
To surpass this i am using the following fix inside My Activity
#Override
public void onBackPressed() {
// If the fragment exists and has some back-stack entry
if (myFragment != null && myFragment.getChildFragmentManager().getBackStackEntryCount() > 0) {
// Get the fragment fragment manager - and pop the backstack
myFragment.getChildFragmentManager().popBackStack();
}
// Else, nothing in the direct fragment back stack
else {
// Let super handle the back press
super.onBackPressed();
}
}
I've solved in the following way:
1st solution
#Override
public void onBackPressed() {
FragmentManager fragmentManager = getFragmentManager();
int backCount = fragmentManager.getBackStackEntryCount();
if(backCount > 1) {
super.onBackPressed();
} else {
finish();
}
}
2nd solution
#Override
public void onBackStackChanged() {
FragmentManager fragmentManager = getFragmentManager();
int backCount = fragmentManager.getBackStackEntryCount();
if(backCount == 0) {
finish();
}
}
These allow you to exploit the Android stack when you replace your fragment:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, yourFragment)
.addToBackStack(null).commit();
When you press back button inside your fragment onBackPressed() method of your activity will be called if you have declared that..So handling back button for fragments within navigation drawer can be one 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();
Now you can replace finish() for fragmentManager.popBackStack(), method of android.support.v4.app.FragmentManager

Get previous fragment back

Here is my code snippet:
I want to create a new fragment initially, but if the fragment is already created the i want to show the previous fragment;
But every time a new fragment is initialise.
#Override
protected void onCreate(Bundle savedInstanceState) {
.
.
showFragment(FRAGMENT_ADD_DETAILS);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(currentFragment==FRAGMENT_ADD_DETAILS){
finish();
}else{
showFragment(FRAGMENT_ADD_DETAILS);
}
break;
case R.id.menu_action_next:
showFragment(FRAGMENT_INVITE_FRIENDS);
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
.
.
return true;
}
private void showFragment(int fragmentType) {
Log.d(TAG,"showFragment : "+fragmentType);
FragmentManager fragmentManager = getFragmentManager();
Fragment prevFragment = fragmentManager.findFragmentByTag(String.valueOf(fragmentType));
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (prevFragment == null) { //create a fresh instance of fragment
Log.d(TAG,"Initialize new fragment");
Fragment newFragment;
if (fragmentType == FRAGMENT_ADD_DETAILS) {
newFragment = new NewDetailsFragment();
} else {
newFragment = new NewInviteFragment();
}
fragmentTransaction.replace(R.id.ant_container_layout, newFragment);
fragmentTransaction.addToBackStack(String.valueOf(fragmentType));
} else {//just reuse the previous fragment
Log.d(TAG,"Re-Using previous fragment");
fragmentTransaction.replace(R.id.ant_container_layout, prevFragment);
}
fragmentTransaction.commit();
}
Please Help!
You never add any tags to your fragments, so you cannot find them by using findFragmentByTag().
When you replace a fragment, instead of
fragmentTransaction.replace(R.id.ant_container_layout, newFragment);
use the overloaded method that accepts a tag:
fragmentTransaction.replace(R.id.ant_container_layout, newFragment, String.valueOf(fragmentType));
You try to restore your fragments in onCreate() of your activity but it seems that you haven't retained your fragments. They are thus destroyed together with the activity and when the activity is created again, new fragments are created.

Categories

Resources