Evolution
Evolution

Reputation: 31

Fragment is called twice on screen rotation

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;

    }

Upvotes: 3

Views: 2621

Answers (1)

shaik subhani
shaik subhani

Reputation: 169

Add this code to your Activity's onCreate method:

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
}

Upvotes: 6

Related Questions