0
我已經實現了一個包含兩個選項卡的簡單活動。這些選項卡與碎片相關聯:第一個是MapFragment
,第二個是ListFragment
。 我這樣overrid的onCreate
方法:方向變化時地圖上的標記消失
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.path_summary);
final ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.addTab(actionbar.newTab()
.setText("Map")
.setTabListener(new TabListener<com.google.android.gms.maps.MapFragment>(
this, "map", com.google.android.gms.maps.MapFragment.class)));
actionbar.addTab(actionbar.newTab()
.setText("List")
.setTabListener(new TabListener<com.example.northfinder.PathListFragment>(
this, "list", com.example.northfinder.PathListFragment.class)));
if (savedInstanceState != null) {
actionbar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
然後,我需要在地圖上寫(添加標記),所以我重寫的onResume方法:
protected void onResume() {
super.onResume();
FragmentManager fm = getFragmentManager();
Fragment f = fm.findFragmentByTag("map");
if(f!= null && f.isAdded())
setUpMapIfNeeded((MapFragment)f);
}
其中setUpIfNeeded
是定義如下:
private static void setUpMapIfNeeded(MapFragment mMapFragment) {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
mMap = mMapFragment.getMap();
}
if (mMap != null) {
mMap.clear()
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
所有的作品都不錯。當活動開始時,標記正確添加到MapFragment中,當我更改標籤,然後回到第一個標籤時,標記仍然可見。
我只有一個問題:當方向改變時,標記消失。爲什麼?
看到裏面的問題http://stackoverflow.com/questions/5123407/losing-data-when-rotate-screen –
但是,當方向變化Activity應該被重新創建,所以onCreate和onResume都應該被執行。對? – GVillani82
是的,你說得對。 –