2012-07-02 62 views
4

我實現了一個基於本教程中我的佈局:http://android-developers.blogspot.hu/2011/02/android-30-fragments-api.html方向改變後,片段的optionsmenu不會消失

的區別是:

  • 我有不同的片段展示的基礎上,選擇在左 列表
  • 「詳細信息碎片」(那些前來右)有不同的選擇功能表的

我的問題是,如果我已經從左側選擇了一些東西,然後將手機旋轉到縱向,最後一個選項菜單仍然存在並且可見。

我認爲問題來自上次活動的「細節」片段在方向改變後重新創建。以測試它,我創建了這兩種方法:

@Override 
public void onStart() { 
    super.onStart(); 
    setHasOptionsMenu(true); 
} 

@Override 
public void onStop() { 
    super.onStop(); 
    setHasOptionsMenu(false); 
} 

而且我展示正確的片段是這樣的:

case R.id.prefs_medicines: 
     if (mDualPane) { 


      // Check what fragment is shown, replace if needed. 
      View prefsFrame = getActivity().findViewById(R.id.preferences); 
      if (prefsFrame != null) { 
       // Make new fragment to show this selection. 
       MedicineListF prefF = new MedicineListF(); 

       // Execute a transaction, replacing any existing 
       // fragment with this one inside the frame. 
       FragmentTransaction ft = getFragmentManager().beginTransaction(); 
       ft.replace(R.id.preferences, prefF); 
       ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
       ft.commit(); 
      } 

     } else { 
      // Otherwise we need to launch a new activity to display 
      // the dialog fragment with selected text. 
      Intent intent = new Intent(); 
      intent.setClass(getActivity(), MedicinePrefsActivity.class); 
      startActivity(intent); 
     } 
     break; 

在我的「細節」片段中的一個。當我調試它時,onstart在旋轉後被調用。

在圖片的問題:

1:在景觀沒關係 Landscape mode http://img834.imageshack.us/img834/8918/error1d.png

2:人像:optionsmenu不需要 Portrait mode http://img860.imageshack.us/img860/8636/error2r.png

我怎樣才能在肖像擺脫optionsmenu的模式?

回答

5

我有同樣的問題,並解決它通過設置setHasOptionsMenu(真)在片段只有當savedInstanceState爲空。如果onCreate獲得一個包,那麼該片段正在恢復方向改變爲肖像,所以不要顯示菜單。

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    if(savedInstanceState == null) { 
     setHasOptionsMenu(true); 
    } 
}  
+0

這解決了我的問題。 – Axel