片段在屏幕旋转时调用两次

时间:2017-03-01 04:59:45

标签: android android-fragments

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

    }

1 个答案:

答案 0 :(得分:5)

简单添加此代码

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

 FragmentOne fragment = new FragmentOne();

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