我有一个基本布局,里面有FragmentLayout。我还有一个导航抽屉,当点击抽屉的不同元素时,我会更改FragmentLayout的内容,如下所示:
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new WhateverFragment());
fragmentTransaction.commit();
我正在使用的一个片段中有一个MapView。我在onCreateView函数上初始化mapView,如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map, container, false);
mapView = (MapView) v.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.onResume();//needed to get the map to display immediately
MapsInitializer.initialize(this.getActivity());
mapView.getMapAsync(this);
return v;
}
但每次切换到此片段时都会调用此函数,因此每次都会重置并重新加载映射(因此不会保留标记或任何内容)。
我应该在哪里放置这个mapView初始化代码,以便不是每次都调用它?
答案 0 :(得分:0)
不要在xml中初始化MapView
,而是考虑在代码中手动创建,并在片段中保留WeakReference
。
答案 1 :(得分:0)
嗨,您可以在片段中初始化地图oncreate,然后像这样调用
调用 setRetainInstance(true)
mapView = (MapView) v.findViewById(R.id.map);
MapsInitializer.initialize(this.getActivity());
mapView.getMapAsync(this);
另一种解决方案,
开始片段时调用此方法,
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
Intent i = new Intent("TAG_REFRESH");
lbm.sendBroadcast(i);
你的碎片:
public class MyFragment extends Fragment {
MyReceiver r;
public void refresh() {
//yout code in refresh.
Log.i("Refresh", "YES");
}
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(context).unregisterReceiver(r);
}
public void onResume() {
super.onResume();
r = new MyReceiver();
LocalBroadcastManager.getInstance(context).registerReceiver(r,
new IntentFilter("TAG_REFRESH"));
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MyFragment.this.refresh();
}
}
希望这会对你有所帮助