4

I am using the latest design support library. And I have set up the navigation view with four fragments as its menu items.

I would like to have my first fragment (i.e first item in the navigation drawer)opened when the user starts the app.

By default it shows me the MainActivity layout.

I tried

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

But the above code does not do anything.

Vivek_Neel
  • 1,313
  • 1
  • 14
  • 24
  • Here is an example http://thegeekyland.blogspot.com/2015/11/navigation-drawer-how-set-selected-item.html – Arlind Dec 04 '15 at 19:21

2 Answers2

8

Do you use fragment container layout? If not, add this to your activity_main.xml

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

In your Activity override onCreate method:

@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();
    }
}

Instead of MainActivityFragment() call your fragment which you want to display at the beginning.

Damian Kozlak
  • 6,917
  • 10
  • 44
  • 51
7
navigationView.getMenu().getInt(0).setChecked(true);

replace by

navigationView.getMenu().getItem(0).setChecked(true);
Mansukh Ahir
  • 3,833
  • 5
  • 38
  • 61