I'm attaching the fragment (many fragments to FrameLayout
) of an Activity
each fragment has its own view inflated in onCreateView()
.
Now,
If I rotate the screen Landscape/Protrait the onCreateView()
of the fragment is called instead of calling its attached Activity's onCreate()
method. Because of this the view are rendered twice.
I want the Activity's onCreate()
to be called every time when there is a config changes. Is it possible?
Activity : MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
getSupportFragmentManager().beginTransaction()
.add(R.id.layout_replace, new MyFragment()).commit();
}
Fragment : MyFragment.java
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return (ScrollView)inflater.inflate(R.layout.some_layout, container, false);
}
The onActivityCreated() method is called after onCreateView() and before onViewStateRestored() . onDestroyView() : Called when the View previously created by onCreateView() has been detached from the Fragment . This call can occur if the host Activity has stopped, or the Activity has removed the Fragment .
If you were using Fragment extended to your class and have written onCreateView() method, then it would have been called only twice after your onAttach() and onDestroyView() if you are still on same fragment.
OnCreateView is called twice without pressing back button or on any other event. Its called twice, once when fragment initially creates and again just after findNavController. navigate event.
Fixed this!!
Actual problem was with FragmentTransaction
for which I'm adding fragments using .add()
which causes the view to be populated twice.
Instead use :
.replace(R.id.yourId, fragment)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With