0

According to the tutorials that I have read, the method addToBackStack(null) is the right way to get back to the previous fragment or activity loaded. But on my part, the addToBackStack() is missing on the ft object that holds the FragmentManager class. Here's my code.

conteach.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        SpecificArticleFragment spcf = new SpecificArticleFragment();
                        Bundle args = new Bundle();
                        args.putString("art_id", v.getTag().toString());
                        spcf.setArguments(args);

                        FragmentManager ft = getFragmentManager();
                        ft.beginTransaction().replace(R.id.content_frame, spcf).commit();
                     //I know that I should put the ft.addToBackStack(null) code here but the addToBackStack(null) method does not exist on the ft object
                    }
                 });

Anyway, according to my understanding if the SpecificArticleFragment fragment loads, I can go back to the existing fragment where the code above was located. What is the best way to fix this?

2 Answers2

1

you are using Fragment manager but addtobackStack is a metod of FragmentTransaction class. see below code .

 // Create new fragment and transaction
    Fragment newFragment = new ExampleFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();
vishal jangid
  • 2,967
  • 16
  • 22
1
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

    Fragment fragment= new Example();
    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.main_fragment, fragment, fragment.getClass().getName());
    ft.addToBackStack(fragment.getClass().getName());
    ft.commit();
Nas
  • 2,158
  • 1
  • 21
  • 38