片段在屏幕旋转上被调用两次

问题描述:

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

    } 
+0

像父'activity' fragment'的'和'交全码manifest' –

+0

当屏幕旋转时,活动的onCreate方法再次获得called.To避免这种情况,在清单中为该活动添加(android:configChanges =“orientation | keyboardHidden”)这一行。 – Ragini

+0

@Ragini在屏幕上旋转,onStart()和onResumeFragments()方法正在从活动中调用。 – Evolution

简单添加以下代码

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 
} 
+0

请提一下,如果答案有用 –

+0

稍微详细一点,当你不添加这个由两次创建的检查片段时,因为android在循环事件之后为你创建它,并且你还在活动#onCreate中创建另一个。 – erhun