Fragment 在屏幕旋转时被调用两次

问题描述 投票:0回答:1

我是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;

    }
android android-fragments
1个回答
6
投票

将此代码添加到您的 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
}
© www.soinside.com 2019 - 2024. All rights reserved.