Is it possible to manually call onCreateView in a Fragment?

Symon_9851 picture Symon_9851 · Jun 20, 2013 · Viewed 33.7k times · Source

Is it possible to manually call the method onCreateView in a Fragment or, if not, is there some way I can simulate this invocation?

I have a FragmentActivity with tabHost. Each tab contains a Fragment and I want to refresh the Fragment's view when I press the "Refresh" button. More specifically, I want to re-call the onCreateView method.

My code currently looks like:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
    view= inflater.inflate(R.layout.fragment_hall, container, false);

    layoutExsternal = (RelativeLayout) view.findViewById(R.id.layoutExsternal);
    layoutHall = (RelativeLayout) view.findViewById(R.id.layoutHall);

    init();

    return view;
 }

  [...]

@Override
public boolean onOptionsItemSelected(MenuItem item) {
      // TODO Auto-generated method stub
     Log.d("itemSelected1", this.getClass().getSimpleName());

     switch (item.getItemId()) {
        case R.id.menu_refresh:

            //HERE I want to insert a method for refresh o redraw

     return true;
     }

return super.onOptionsItemSelected(item);

}

Answer

Matthew Mcveigh picture Matthew Mcveigh · Oct 16, 2013

Sometimes I found FragmentTransaction's replace would not work for replacing a fragment with itself, what does work for me is using detach and attach:

getSupportFragmentManager()
    .beginTransaction()
    .detach(fragment)
    .attach(fragment)
    .commit();

See this question for the difference between remove and detach