我有MainActivity

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fragment_container, AFragment.newInstance(75))
                .commit();
    }

    @Override
    public void onBackPressed() {
       if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
           getSupportFragmentManager().popBackStack();
       } else {
           super.onBackPressed();
       }
    }


另外,我有AFragment

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_a, container, false);

        view.findViewById(R.id.show_b_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity();

                appCompatActivity.getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.fragment_container, BFragment.newInstance())
                        .addToBackStack("B")
                        .commit();
            }
        });

        return view;
    }


BFragment只是一个空片段。

我有以下片段生命周期输出:

Open the App:
A - onCreateView
A - onStart
A - onResume

Click R.id.show_b_btn on AFragment:
B - onStart
B - onResume

Click back button:
B - onPause
B - onStop

Close the App:
A - onPause
A - onStop


那么,问题是为什么单击ShowBFragment时AFragment不会调用onPause以及为什么单击后退按钮时AFragment不会调用onResume?

我认为这是因为我使用了.add()并且BFragment只是覆盖了AFragment,所以当BFragment可见时,AFragment也会“存活”,对吗?

最佳答案

只需更换

getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fragment_container, AFragment.newInstance(75))
                .commit();




getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container, AFragment.newInstance(75))
                .commit();


如果在容器上使用FragmentTransaction.add,就会发生这种情况。您添加的片段将放置在现有片段的顶部。如果您使用FragmentTransaction.replace(R.id.container,fragment),它将删除容器中已经存在的所有片段,并将新片段添加到同一容器中

您也可以参考下面的链接

Difference between add(), replace(), and addToBackStack()

08-18 16:57