方法 addToBackStack(null) 不在 FragmentManager Class 的 属性 上。这是回到之前 fragment/activity 的正确方法吗?

Method addToBackStack(null) is not on the property of the FragmentManager Class. Is this the proper way to go back to the previous fragment/activity?

根据我阅读的教程,方法 addToBackStack(null) 是返回上一个片段或 activity 加载的正确方法。但就我而言,在包含 FragmentManager class 的 ft 对象上缺少 addToBackStack()。这是我的代码。

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
                    }
                 });

无论如何,根据我的理解,如果 SpecificArticleFragment 片段加载,我可以回到上面代码所在的现有片段。解决此问题的最佳方法是什么?

您正在使用片段管理器,但 addtobackStackFragmentTransaction class 的一个方法。见下面的代码。

 // 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();
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();