22

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);

}
4

3 回答 3

35

有时我发现 FragmentTransaction 的替换不适用于用自身替换片段,对我有用的是使用分离和附加:

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

请参阅此问题以了解删除和分离之间的区别

于 2013-10-16T16:55:33.630 回答
9

我已经解决了我的问题。我用自己替换当前片段,但在我保存当前片段的引用之前,我关闭当前片段调用 onDestroy() 的生命周期。我用“newFragment”变量回忆它。

         

switch (item.getItemId()) { case R.id.menu_refresh: //THIS IS THE CODE TO REFRESH THE FRAGMENT. FragmentManager manager = getActivity().getSupportFragmentManager(); FragmentTransaction ft = manager.beginTransaction(); Fragment newFragment = this; this.onDestroy(); ft.remove(this); ft.replace(container.getId(),newFragment); //container is the ViewGroup of current fragment ft.addToBackStack(null); ft.commit(); return true; }

于 2013-06-26T07:36:15.223 回答
3

您可以让替换按钮用片段的新实例替换当前布局。

// onButtonClick
SomeFragment fragment = new SomeFragment();
getFragmentManager().beginTransaction().replace(R.id.current_layout, fragment).commit();
于 2013-06-24T20:56:26.090 回答