片段在屏幕旋转时被调用两次 [英] Fragment is called twice on screen rotation

查看:65
本文介绍了片段在屏幕旋转时被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android新手,更改屏幕方向后会遇到此问题.每当屏幕方向更改时, fragment 都会被调用两次.以下是我的代码示例.我检查了其他帖子,但找不到答案.任何人都可以指导我.

I am new to android, and i am facing this problem when the screen orientation is changed. The fragment gets called twice whenever screen orientation changes. Below is the sample of my code. I checked other posts, but couldnt find answer. Anyone guide me through this.

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;

    }

推荐答案

简单添加此代码

 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
} 

这篇关于片段在屏幕旋转时被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆