Android Fragments 在屏幕旋转时调用Fragment两次

e5nqia27  于 2023-10-19  发布在  Android
关注(0)|答案(1)|浏览(144)

我是Android的新手,当屏幕方向改变时,我就面临着这个问题。每当屏幕方向改变时,fragment会被调用两次。下面是我的代码示例。我检查了其他帖子,但找不到答案。任何人都可以指导我。

public class SampleFragment extends Fragment {

    static final String TAG_NAME = SampleFragment.class.getSimpleName();

    List<PhrToolBar> mToolBarList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        DaggerHelper.getAppProviderComponent().inject(this);

        mRootView = null;

        getActivity().setTitle("Personal Health Records");

        mRootView = inflater.inflate(R.layout.sample_phr_main_fragment, container, false);

        mBinding = DataBindingUtil.bind(mRootView);
        mBinding.setViewModel(mViewModel);

        setHasOptionsMenu(true);

        return mRootView;

    }
egdjgwm8

egdjgwm81#

将以下代码添加到Activity的onCreate方法中:

if (savedInstanceState == null) {
    // only create fragment if activity is started for the first time
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    FragmentOne fragment = new FragmentOne();

    fragmentTransaction.add(R.id.fragment_container, fragment);
    fragmentTransaction.commit();
} else {        
    // do nothing - fragment is recreated automatically
}

相关问题