2015-07-05 55 views
4

我正在使用最新的設計支持庫。我已經設置了四個片段作爲其菜單項的導航視圖。在導航抽屜中設置默認選定選項

我想在用戶啓動應用程序時打開我的第一個片段(即導航抽屜中的第一項)。

默認情況下,它向我顯示MainActivity佈局。

我試圖

navigationView.getMenu().getInt(0).setChecked(true); 

但上面的代碼不會做任何事情。

+0

這裏取而代之的是一個例子http://thegeekyland.blogspot.com/2015/11/navigation-drawer-how-set-selected-item.html – Arlind

回答

8

你使用片段容器佈局嗎?如果不是,將它添加到您的activity_main.xml

<FrameLayout 
    android:id="@+id/fragment_container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

在你的活動覆蓋onCreate方法:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    if (savedInstanceState == null) { 
     getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MainActivityFragment()).commit(); 
    } 
} 

代替MainActivityFragment()打電話,你想在一開始就顯示你的片段。

+0

是的,我使用容器。感謝您的解決方案。 –

+2

請注意,您應該在'if(savedInstanceState == null)'檢查中放置'replace()'調用 - 否則您的片段將在旋轉時被替換。 – ianhanniballake

+0

[看這個解決方案](http://stackoverflow.com/questions/31233279/navigation-drawer-how-set-selected-item-at-startup/33521048#33521048) – GFPF

7
navigationView.getMenu().getInt(0).setChecked(true); 

通過

navigationView.getMenu().getItem(0).setChecked(true); 
+0

[看這個解決方案](http:// stackoverflow.com/questions/31233279/navigation-drawer-how-set-selected-item-at-startup/33521048#33521048) – GFPF