Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fragment onCreateView called many times

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);
}
like image 880
yashhy Avatar asked Apr 23 '14 15:04

yashhy


People also ask

What is called after onCreateView?

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 .

How often is Onviewcreated called?

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.

Why is Onviewcreated twice in Android app using navigation components?

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.


1 Answers

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)

like image 182
yashhy Avatar answered Oct 11 '22 02:10

yashhy