I have created a new android studio project using the navigation drawer activity. Currently, the main activity starts when the app is loaded (which is fine), but I want to associate this main activity with a particular menu item in the drawer such that 1) when this menu item is selected the main activity will load, and 2) I want that menu item to be selected/highlighted by default when the app first starts
I think I would handle issue 1 with intents in the onNavigationItemSelected
method, but I'm not sure how to have a menu item selected by default.
I've searched around and the only solutions I've found refer to fragments, but I'm not using fragments in this project (and those solutions didn't work). For example I have tried selectItem(0);
in onCreate()
, and navigationView.getMenu().getItem(0).setChecked(true);
but neither seem to work.
Here is my base code:
MainActivity.java
:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "FAB Pressed", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
activity_main_drawer.xml
:
<item android:title="Menu">
<menu>
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_new"
android:icon="@drawable/ic_menu_share"
android:title="@string/nav_new" />
<item
android:id="@+id/nav_start"
android:icon="@drawable/ic_menu_slideshow"
android:title="@string/nav_start" />
<item
android:id="@+id/nav_delete"
android:icon="@drawable/ic_menu_manage"
android:title="@string/nav_delete" />
</group>
</menu>
</item>
Not much has changed from the starting project apart from the menu items. I want to have the New
menu item selected by default as I want to associate that item with the MainActivity
You only need to add code:
navigationView.setCheckedItem(R.id.nav_new);