让我们看看这张照片:
在Android教程中,每次FragmentA
替换为FragmentB
时,都会创建FragmentB
的新实例。
让我们查看下一个案例FragmentA
至FragmentB
然后返回(按)至FragmentA
并再次转至FragmentB
。也许如果FragmentB
的旧实例仍然活着会更好地使用它(只更新数据)而不是创建新实例?有没有简单的方法呢?
答案 0 :(得分:0)
尝试使用fragmentTransaction.show方法重用现有片段。
使用以下方法切换片段,如果已经添加了片段,它将显示片段。
public void switchFragment (Fragment oldFragment, Fragment newFragment, int frameId) {
boolean addFragment = true;
FragmentManager fragmentManager = getFragmentManager ();
String tag = newFragment.getArguments ().getString (BaseFragment.TAG);
Fragment fragment = fragmentManager.findFragmentByTag (tag);
// Check if fragment is already added
if (fragment != null && fragment.isAdded ()) {
addFragment = false;
}
// Hide previous fragment
String oldFragmentTag = oldFragment.getArguments ().getString (BaseFragment.TAG);
if (!tag.equals (oldFragmentTag)) {
FragmentTransaction hideTransaction = fragmentManager.beginTransaction ();
Fragment fragment1 = fragmentManager.findFragmentByTag (oldFragmentTag);
hideTransaction.hide (fragment1);
hideTransaction.commit ();
}
// Add new fragment and show it
FragmentTransaction addTransaction = fragmentManager.beginTransaction ();
if (addFragment) {
addTransaction.add (frameId, newFragment, tag);
addTransaction.addToBackStack (tag);
}
else {
newFragment = fragmentManager.findFragmentByTag (tag);
}
addTransaction.show (newFragment);
addTransaction.commit ();
}
答案 1 :(得分:0)
您可以为片段使用简单的Singleton,
public class FragmentGoogleMap extends Fragment implements OnMapReadyCallback {
MapView mapView;
GoogleMap googleMap;
private static FragmentGoogleMap instance = null;
private FragmentGoogleMap() {
}
public static FragmentGoogleMap getInstance(){
if(instance == null){
instance = new FragmentGoogleMap();
}
return instance;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
frome活动你可以获得实例
private FragmentGoogleMap fragmentGoogleMap;
private FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
fragmentGoogleMap = FragmentGoogleMap.getInstance();
fragmentManager.beginTransaction().replace(R.id.fragment_map_container,fragmentGoogleMap).commit();
}