Fragment re-created on bottom navigation view item selected
Asked Answered
P

16

67

Following is my code for bottom navigation view item selected

bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {  
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment fragment = null;
    switch (item.getItemId()) {
        case R.id.action_one:
            // Switch to page one
            fragment = FragmentA.newInstance();
            break;
        case R.id.action_two:
            // Switch to page two
            fragment = FragmentB.newInstance();
            break;
        case R.id.action_three:
            // Switch to page three
            fragment = FragmentC.newInstance();
            break;
    }
    getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment,"TAG").commit();
    return true;
}
});

Now my problem is every time fragment is re-created and don't want fragment to be recreated every time I also tried adding addToBackStack(null) but it this case on back button press keeps popping fragments from stack which I don't want.

Is there any way to display fragments on bottom navigation bar selected without re-creating fragment

Pershing answered 21/2, 2017 at 9:6 Comment(12)
To avoid that, I have create a map : Map<int, Fragment> and each fragment have a static id. I create all Fragment in onCreate of the Activity. But it's not recommended. You can add the fragment in the backstack with a unique tag like Fragment.class.getSimpleName(), then find it with findFragmentByTag and commit him again. Be sure to add each Fragment one time to the backstackHomeopathy
Hi Raphael as I said I don't want to add to it to backstack since it disturbs on back press implementationPershing
For that you can Override onBackPressed() in your Activity. Comment super.onBackPressed()Homeopathy
no but there are some fragments other than these which will be added to stack if user performs action. I just don't want to add fragments associated with bottom navvigation view to backstack at same time dont want to recreate themPershing
You don't want to recreate them for the view or something else in there code ?Homeopathy
for view i dont want to re createPershing
You can't, the view will always be recreate.Homeopathy
there apps like google news stand do the samePershing
Oh, I see, I just install Google NewsStand, and what you talking about it's the menu on the bottom right ?Homeopathy
no click on bottom navigation bar items see it does not creates fragments again and againPershing
@Pershing will please share me the idea , how to retain the state of click Bottom Nevigation item while on backpressed.?Athanasian
if you use the android navigation architecture component, see this: https://mcmap.net/q/159130/-is-there-a-way-to-keep-fragment-alive-when-using-bottomnavigationview-with-new-navcontrollerDietetics
L
26

With support library v26 you can do this

FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();

Fragment curFrag = mFragmentManager.getPrimaryNavigationFragment();
if (curFrag != null) {
    fragmentTransaction.detach(curFrag);
}

Fragment fragment = mFragmentManager.findFragmentByTag(tag);
if (fragment == null) {
    fragment = new YourFragment();
    fragmentTransaction.add(container.getId(), fragment, tag);
} else {
    fragmentTransaction.attach(fragment);
}

fragmentTransaction.setPrimaryNavigationFragment(fragment);
fragmentTransaction.setReorderingAllowed(true);
fragmentTransaction.commitNowAllowingStateLoss();
Lanna answered 25/7, 2017 at 10:48 Comment(9)
For a complete example you can look at this git repo github.com/okaybroda/FragmentStateManagerLanna
Would you say this is the best way to handle navigation between three destinations when you want to keep the state/list positions etc when moving back and forth? Are there any caveats to using this method? Possible memory leaks or anything to be aware of? I'm not 100% sound on lifecycle quite yetMaintenance
Would it be better to do this or somehow restore instance state is what I really want to know I think!Maintenance
It did not seem to hold fragments in memory; it just somehow made page fragments look layered (page1 looked through below page2).Deeplaid
I'd like to improve your nice snippet with the condition: if (curFrag != null && curFrag != fragment ). In you code, if a fragment is already on screen, when I click the same bottom button, fragment will be detached showing a black pagePengelly
@Pengelly thanks for the highlight. I have made edits to the snippet by detaching first before attaching.Lanna
using show hide instead of attach detach works better. It won't restart fragment's lifecycleEmbellish
@Embellish that works too but it will hold up the views in memoryLanna
Yes that's what I've wanted in the first place :) thank you for your answers, it helped @LannaEmbellish
A
16

I faced the same problem and finally i i found the solution, you can try this code. it's work for me.

import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
public BottomNavigationView bv;
public home_fragment home;
public account_fragment afrag;
public other_fragment other;
public FrameLayout fr;
android.support.v4.app.Fragment current;
//public FragmentTransaction frt;
    public static int temp=0;
    final Fragment fragment11 = new account_fragment();
    final Fragment fragment22 = new home_fragment();
    final Fragment fragment33 = new other_fragment();
    final FragmentManager fm = getSupportFragmentManager();
    Fragment active = fragment11;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bv=(BottomNavigationView) findViewById(R.id.navigationView);


        fm.beginTransaction().add(R.id.main_frame, fragment33, "3").hide(fragment33).commit();
        fm.beginTransaction().add(R.id.main_frame, fragment22, "2").hide(fragment22).commit();
        fm.beginTransaction().add(R.id.main_frame,fragment11, "1").commit();
bv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.account:
                        fm.beginTransaction().hide(active).show(fragment11).commit();
                        active = fragment11;
                        return true;

                    case R.id.home1:
                        fm.beginTransaction().hide(active).show(fragment22).commit();
                        active = fragment22;
                        return true;

                    case R.id.other:
                        fm.beginTransaction().hide(active).show(fragment33).commit();
                        active = fragment33;
                        return true;
                }
                return false;
            }
        });
      bv.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
          @Override
          public void onNavigationItemReselected(@NonNull MenuItem item) {
              Toast.makeText(MainActivity.this, "Reselected", Toast.LENGTH_SHORT).show();

          }
      });


    }

}
Aran answered 6/9, 2018 at 22:56 Comment(4)
Hat's off to you man! Really appreciate your work. You made my day. Thank you!Erlanger
Definitely the cleanest solution I think. And it's flexible - if you need to recreate the fragment, you just re-assign the relevant fragment variable. Thanks a lot!Hotspur
But this solution is not scalable. You will have to modify your code every time you want to add a new fragment.Justly
with this code navigation between specified fragments is flawless but we have to handle many other things if using nav componentsSedum
C
15

This seemed to work well for me. Instead of attaching and detaching, i use show or hide to maintain fragment state.

    public void changeFragment(Fragment fragment, String tagFragmentName) {

        FragmentManager mFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();

        Fragment currentFragment = mFragmentManager.getPrimaryNavigationFragment();
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment);
        }

        Fragment fragmentTemp = mFragmentManager.findFragmentByTag(tagFragmentName);
        if (fragmentTemp == null) {
            fragmentTemp = fragment;
            fragmentTransaction.add(R.id.frame_layout, fragmentTemp, tagFragmentName);
        } else {
            fragmentTransaction.show(fragmentTemp);
        }

        fragmentTransaction.setPrimaryNavigationFragment(fragmentTemp);
        fragmentTransaction.setReorderingAllowed(true);
        fragmentTransaction.commitNowAllowingStateLoss();
    }

And this is how i use it

     private void initViews() {
        BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener
                (new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        Fragment selectedFragment = null;
                        switch (item.getItemId()) {
                            case R.id.explore:
                                changeFragment(new ExploreFragment(), ExploreFragment.class
                                        .getSimpleName());
                                toggleViews(true, "");
                                break;
                            case R.id.favorite:
                                changeFragment(new FavoriteFragment(), FavoriteFragment.class
                                        .getSimpleName());
                                toggleViews(false, "Favorites");
                                break;
                            case R.id.venue:
                                changeFragment(new VenueFragment(), VenueFragment.class.getSimpleName());
                                toggleViews(false, "Venues");
                                break;
                            case R.id.profile:
                                changeFragment(new ProfileFragment(), ProfileFragment.class
                                        .getSimpleName());
                                toggleViews(false, "Profile");
                                break;
                        }
                        return true;
                    }
                });

        //Manually displaying the first fragment - one time only
        changeFragment(new ExploreFragment(), ExploreFragment.class
                .getSimpleName());

    }
Coppersmith answered 8/11, 2018 at 8:20 Comment(0)
B
12

This solution stops a fragment from being re-created when the currently selected nav button is clicked again. However, a new fragment will be created every time the user clicks a different nav button.

Just add this line to avoid re-created Fragment from BottomNavigationView

 bottomNavigation.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
            @Override
            public void onNavigationItemReselected(@NonNull MenuItem item) {
             // do nothing here   
            }
        });

Or with a lambda:

bottomNavigation.setOnNavigationItemReselectedListener(item -> { });
Bagnio answered 2/3, 2020 at 6:42 Comment(3)
And you are real hero! you are life sever!Vituperate
@DilipHirapara Dhanyawad mitra.. :DBagnio
setOnNavigationItemReselectedListener is deprecated, change to setOnItemReselectedListenerMazonson
G
8

Be careful when using replace. Even if providing a fragment that already exists in memory, replace will restart the fragment's lifecycle. To avoid a restart, the transaction object's methods includes add, show, and hide, which can be used to show the correct fragment without restarting it.

private fun switchFragment(selectedTabIndex: Int) {
    val previousTabIndex = this.currentTabIndex
    this.currentTabIndex = selectedTabIndex

    val transaction = supportFragmentManager.beginTransaction()
    val tag = fragments[this.currentTabIndex].tag

    // if the fragment has not yet been added to the container, add it first
    if (supportFragmentManager.findFragmentByTag(tag) == null) {
        transaction.add(R.id.container, fragments[this.currentTabIndex], tag)
    }

    transaction.hide(fragments[previousTabIndex])
    transaction.show(fragments[this.currentTabIndex])
    transaction.commit()
}
Groschen answered 9/8, 2017 at 15:35 Comment(4)
You used slightly confusing wording there, just to clarify: replace doesn't restart a fragments's life cycle as it is added to the UI - it ends the fragment currently attached then adds the new frag, which we can only assume was previously destroyed if removed or it's being added for the first time. So it will surely be starting over yes but not because replace is forcing it to. Essentially replace = remove(oldFrag) then add(newFrag).Maintenance
What is currentTabPosition? android.support.design.widget.BottomNavigationView does not seem to have that property.Deeplaid
One should be very careful while using findFragmentByTag ... it's better to avoid it altogether :PRoemer
@Groschen can you clarify the above comments please? What is the index and currentTabPosition and what if this switchFragment method is in BaseActivity. Can you post an example with small activity or git gist. Thanks as this answer seems to be incomplete.Waddle
H
7

Try this :

bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment fragment = null;
                    Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container);
                    switch (item.getItemId()) {
                        case R.id.action_one:
                            // Switch to page one
                            if (!(currentFragment instanceof FragmentA)) {
                                fragment = FragmentA.newInstance();
                            }
                            break;
                        case R.id.action_two:
                            // Switch to page two
                            if (!(currentFragment instanceof FragmentB)) {
                                fragment = FragmentB.newInstance();
                            }
                            break;
                        case R.id.action_three:
                            // Switch to page three
                            if (!(currentFragment instanceof FragmentC)) {
                                fragment = FragmentC.newInstance();
                            }
                            break;
                    }
                    getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, "TAG").commit();
                    return true;
                }
            });

That will get the current fragment in your container and if you click again on this fragment that will not re add the fragment.

Homeopathy answered 21/2, 2017 at 10:35 Comment(6)
How i can redirect to home page when i click on back button...please help me sirHarlotry
You can Override the fucntion onBackPressed on your main Activity.Homeopathy
In your code, If first FragmentA loaded, After click on second than second fragment loaded, after that If user click on firstFragment then is also recreate.Codification
@MiteshVanaliya Yes, if you want to not recreate every time the fragment, store the variable, or put all the fragment inside a ViewPagerand change the current item.Homeopathy
@Raphael Teyssandier current fragment returning nullReardon
@Reardon That means you no fragment in your containerHomeopathy
B
7

setOnNavigationItemReselectedListener would be a better solution for that

Bierman answered 2/6, 2017 at 10:44 Comment(1)
I do agree with youEnrique
S
4

The best way i found to do it.

private void replace_fragment(Fragment fragment) {

        String tag = fragment.getClass().getSimpleName();
        FragmentTransaction tr = getSupportFragmentManager().beginTransaction();

        Fragment curFrag = getSupportFragmentManager().getPrimaryNavigationFragment();
        Fragment cacheFrag = getSupportFragmentManager().findFragmentByTag(tag);

        if (curFrag != null)
            tr.hide(curFrag);

        if (cacheFrag == null) {
            tr.add(R.id.main_frame, fragment, tag);
        } else {
            tr.show(cacheFrag);
            fragment = cacheFrag;
        }

        tr.setPrimaryNavigationFragment(fragment);
        tr.commit();

    }
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {
                case R.id.nav_posts:
                    replace_fragment(new PostsFragment());
                    return true;
                case R.id.nav_stores:
                    replace_fragment(new StoresFragment());
                    return true;
                case R.id.nav_chats:
                    replace_fragment(new DiscussionsFragment());
                    return true;
                case R.id.nav_account:
                    replace_fragment(new ProfileFragment());
                    return true;
            }
            return false;
        }
    };
Sheath answered 20/12, 2019 at 10:48 Comment(0)
H
3

Use setOnNavigationItemReselectedListener like this:

private BottomNavigationView.OnNavigationItemReselectedListener onNavigationItemReselectedListener
            = new BottomNavigationView.OnNavigationItemReselectedListener() {

        @Override
        public void onNavigationItemReselected(@NonNull MenuItem item) {
            Toast.makeText(MainActivity.this, "Reselected", Toast.LENGTH_SHORT).show();
        }
    };

and call it using:

navigation.setOnNavigationItemReselectedListener(onNavigationItemReselectedListener);
Highway answered 3/12, 2017 at 16:55 Comment(5)
How does this answer the question?Whitney
@Timuçin whatever you perform inside this function, it will be performed on item reselect, so if you do not wish to create a new fragment then leave it empty.Highway
Not even going inside the reselect function.Embowed
@Timuçin when the reselect listener is set, the normal one won't be fired on item reselection.Fantastically
In 2019, item reselection is only triggered when you select the current item on are on again. Probably useful for something like scroll to top if the current fragment houses a vertical list.Combinative
E
1

I've improved @Viven's answers and written it with Kotlin. My version instantiates fragment only for the first time, hides/shows. I'm new at Kotlin so tell me if I can improve anything.

We need to hold a id to tag map:

private val fragmentTags = hashMapOf(
        R.id.action_home to "home_fragment",
        R.id.action_profile to "profile_fragment"
)

The listener code:

bottomNavigation.run {
    setOnNavigationItemSelectedListener { menuItem ->
        supportFragmentManager.beginTransaction()
                .let { transaction ->
                    // hide current fragment
                    supportFragmentManager.primaryNavigationFragment?.let {
                        // if selected fragment's tag is same, do nothing.
                        if (it.tag == fragmentTags[menuItem.itemId]) {
                            return@setOnNavigationItemSelectedListener true
                        }

                        transaction.hide(it)
                    }

                    var fragment  = supportFragmentManager.findFragmentByTag(fragmentTags[menuItem.itemId])

                    if (fragment == null) {
                        // instantiate fragment for the first time
                        fragment = when(menuItem.itemId) {
                            R.id.action_home -> HomeFragment()
                            R.id.action_profile -> ProfileFragment()
                            else -> null
                        }?.also {
                            // and add it 
                            transaction.add(R.id.frame, it, fragmentTags[menuItem.itemId])
                        }
                    } else {
                        // if it's found show it 
                        transaction.show(fragment)
                    }


                    transaction
                            .setPrimaryNavigationFragment(fragment)
                            .setReorderingAllowed(true)
                }.commitNowAllowingStateLoss()

        return@setOnNavigationItemSelectedListener true
    }

    //bottomNavigation things
    itemIconTintList = null
    selectedItemId = R.id.action_home
}
Embellish answered 22/9, 2018 at 17:48 Comment(0)
D
1

I solved this problem by adding a ViewPager to which I delegated all my navigation fragments. Its adapter (FragmentPagerAdapter) doesn't recreate the fragments instances when the user navigates through the BotoomNavigationView.

To achieve this, you have to complete 5 easy steps:

  1. add a ViewPager to your layout;
  2. implement its adapter:

    class YourNavigationViewPagerAdapter(fm: FragmentManager,
                                         private val param1: Int,
                                         private val param2: Int)
    
        : FragmentPagerAdapter(fm) {
    
        override fun getItem(p0: Int) = when(p0) {
            0 -> NavigationFragment1.newInstance(param1, param2)
            1 -> NavigationFragment2.newInstance(param1, param2)
            2 -> NavigationFragment3.newInstance(param1, param2)
            else -> null
        }
    
        override fun getCount() = 3
    }
    
  3. don't forget to set the new adapter:

    yourViewPager.adapter = YourNavigationViewPagerAdapter(supportFragmentManager, param1, param2)
    
  4. set a OnNavigationItemSelectedListener to your BottomNavigationView like the following:

    yourBottomNavigationView.setOnNavigationItemSelectedListener {
    
        when(it.itemId) {
    
            R.id.yourFirstFragmentMenuItem -> {
                yourViewPager.currentItem = 0
                true
            }
    
            R.id.yourSecondFragmentMenuItem -> {
                yourViewPager.currentItem = 1
                true
            }
    
            R.id.yourThirdFragmentMenuItem -> {
                yourViewPager.currentItem = 2
                true
            }
    
    
            else -> false
        }
    }
    
  5. set a OnPageChangeListener to your ViewPager like the following:

    yourViewPager.addOnPageChangeListener(object : 
    ViewPager.OnPageChangeListener {
        override fun onPageScrollStateChanged(p0: Int) {
    
        }
    
        override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
    
        }
    
        override fun onPageSelected(p0: Int) {
            yourBottomNavigationView.menu.getItem(p0).isChecked = true
        }
    
    })
    
  6. enjoy :)

Droll answered 3/11, 2018 at 16:13 Comment(0)
S
1

I wrote an Extension function in Kotlin for the same.

fun FragmentManager.switch(containerId: Int, newFrag: Fragment, tag: String) {

var current = findFragmentByTag(tag)
beginTransaction()
    .apply {

        //Hide the current fragment
        primaryNavigationFragment?.let { hide(it) }

        //Check if current fragment exists in fragmentManager
        if (current == null) {
            current = newFrag
            add(containerId, current!!, tag)
        } else {
            show(current!!)
        }
    }
    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
    .setPrimaryNavigationFragment(current)
    .setReorderingAllowed(true)
    .commitNowAllowingStateLoss()
}
Seddon answered 14/5, 2019 at 6:5 Comment(0)
P
0

There are several test cases involved in proper navigation , I am pasting my code with all test cases checked.

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        switch (item.getItemId()) {
            case R.id.dashboard:
                Fragment fragment;
                fragment = fragmentManager.findFragmentByTag(DashboardFragment.TAG);

                if (fragment == null) {
                    fragment = new DashboardFragment();
                    fragmentTransaction.add(R.id.frame, fragment, DashboardFragment.TAG);
                } else {
                    fragmentTransaction.detach(fragmentManager.getPrimaryNavigationFragment());
                    fragmentTransaction.attach(fragment);
                }
                fragmentTransaction.setPrimaryNavigationFragment(fragment);
                fragmentTransaction.commitNow();
                return true;
            case R.id.expenses:
                fragment = fragmentManager.findFragmentByTag(ExpenseFragment.TAG);
                if (fragment == null) {
                    fragment = new ExpenseFragment();
                    fragmentTransaction.add(R.id.frame, fragment, ExpenseFragment.TAG);
                } else {
                    fragmentTransaction.detach(fragmentManager.getPrimaryNavigationFragment());
                    fragmentTransaction.attach(fragment);
                }
                fragmentTransaction.setPrimaryNavigationFragment(fragment);
                fragmentTransaction.commitNow();
                return true;
            case R.id.vehicle_parts:
                Bundle bundle = new Bundle();
                bundle.putInt("odometer", vehicle.getOdometer());
                bundle.putString("vehicle_id", vehicle.get_id());
                fragment = fragmentManager.findFragmentByTag(PartsFragment.TAG);
                if (fragment == null) {
                    fragment = new PartsFragment();
                    fragment.setArguments(bundle);
                    fragmentTransaction.add(R.id.frame, fragment, PartsFragment.TAG);

                } else {
                    fragmentTransaction.detach(fragmentManager.getPrimaryNavigationFragment());
                    fragmentTransaction.attach(fragment);
                }
                fragmentTransaction.setPrimaryNavigationFragment(fragment);
                fragmentTransaction.commitNow();
                return true;
            case R.id.blog:
                fragment = fragmentManager.findFragmentByTag(BlogFragment.TAG);

                if (fragment == null) {
                    fragment = new BlogFragment();
                    fragmentTransaction.add(R.id.frame, fragment, BlogFragment.TAG);

                } else {
                    fragmentTransaction.detach(fragmentManager.getPrimaryNavigationFragment());
                    fragmentTransaction.attach(fragment);
                }
                fragmentTransaction.setPrimaryNavigationFragment(fragment);
                fragmentTransaction.commitNow();
                return true;
        }
        return false;
Phosphide answered 6/6, 2018 at 6:34 Comment(0)
M
0

Use Cicerone library for handling navigation easily.

https://github.com/terrakok/Cicerone

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
    switch (menuItem.getItemId()) {
        case R.id.save: {
            router.replaceScreen("your fragment1");
            menuItem.setChecked(true);
            break;
        }
        case R.id.search_lessons: {
            router.replaceScreen("your fragment2");
            menuItem.setChecked(true);
            break;
        }
        case R.id.profile_student: {
            router.replaceScreen("your fragment3");
            menuItem.setChecked(true);
            break;
        }

    }
    return false;
}
Mertens answered 8/11, 2019 at 5:52 Comment(0)
M
0

How To stop recreating Fragment when it is Already Visible Using BottomNavigationView

Step 1--

     @Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment fragment = null;
    String valuestring;      
    **if (item.getItemId() == lastSelectedItemId) { // added this
        Log.e( "both id is same","LULL" );
        return true;
    }**
    switch (item.getItemId()) {
       case R.id.navigation_category:
      SetActioBarText( getString( R.string.label_actionbar_categories ) );
            fragment = new CategoryFragment();
            valuestring = "category";
            break;
        case R.id.navigation_favourite:
     SetActioBarText( getString( R.string.label_actionbar_favourites ) );
            fragment = new FavouriteFragment();
            valuestring = "favourites";
            break;
        default:
            throw new IllegalStateException( "Unexpected value: " +                  menuItem.getItemId() );
    }
    return loadFragment( fragment, valuestring ,menuItem);
}

Now Step 2---

    private boolean loadFragment(Fragment fragment, String argument,MenuItem item) {
  
    if (fragment != null) {
       
        transaction = fragmentManager.beginTransaction();
        transaction.addToBackStack( argument );
        transaction.setTransition( FragmentTransaction.TRANSIT_FRAGMENT_FADE );
        transaction.replace( R.id.frame_container, fragment,                         "demofragment").commitAllowingStateLoss();

     lastSelectedItemId= item.getItemId();
    
        return true;
    }
    return false;
}
Milligan answered 7/9, 2020 at 10:20 Comment(0)
T
-1

no need to do this answers. actually what you really need is to save view in specific fragmet.

 private   View view;
if(view == null){
    view = inflater.inflate(R.layout.call_fragment_edited, container, false);

}

so any time when you create new fragment you see current state

Terrijo answered 13/12, 2020 at 8:55 Comment(1)
We should never cache views especially on fragmentsDinerman

© 2022 - 2024 — McMap. All rights reserved.