Android navigation component: how save fragment state

后端 未结 4 1747
灰色年华
灰色年华 2020-12-03 01:15

I use bottomNavigationView and navigation component. Please tell me how I don\'t destroy the fragment after switching to another tab and return to the old one? For example I

4条回答
  •  感情败类
    2020-12-03 01:46

    Declare fragment on the activity & create fragment instance on onCreate method, then pass the fragment instance in updateFragment method. Create as many fragment instances as required corresponding to bottom navigation listener item id.

    Fragment fragmentA;
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    
    fragmentA = new Fragment();
    updateFragment(fragmentA);
    }
    
    public void updateFragment(Fragment fragment) {
    FragmentTransaction transaction = 
    getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.layoutFragment, fragment);
    transaction.commit();
    }
    

    Furthermore be sure you are using android.support.v4.app.Fragment and calling getSupportFragmentManager()

提交回复
热议问题