Is it possible to manually call onCreateView in a Fragment?

China☆狼群 提交于 2019-11-30 06:41:45
Matthew Mcveigh

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

I have resolved my question. I replace the current fragment with itself, but before I have saved a reference of current fragment and then i close life cycle of current fragment invoking onDestroy(). I recall it with "newFragment" variable.

         

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

You can just have your replace button replace the current layout with a new instance of the fragment.

// onButtonClick
SomeFragment fragment = new SomeFragment();
getFragmentManager().beginTransaction().replace(R.id.current_layout, fragment).commit();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!