I have created MainActivity
with NavigationView
. When Activity
is opened I want to automatically select the first item in the navigation d
in menu.xml
remember to mention android:checkable="true"
for single item and android:checkableBehavior="single"
for a group of items.
<item
android:id="@+id/pos_item_help"
android:checkable="true"
android:title="Help" />
<group
android:id="@+id/group"
android:checkableBehavior="single">
<item
android:id="@+id/menu_nav_home"
android:icon="@drawable/ic_home_black_24dp"
android:title="@string/menu_nav_home" />
</group>
then inside NavigationItemSelectedListener
use setCheckedItem(R.id.item_id_in_menu)
to make it selected.
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.pos_item_pos:
navigationView.setCheckedItem(R.id.pos_item_pos);
break;
case R.id.pos_item_orders:
navigationView.setCheckedItem(R.id.pos_item_orders);
break;
default:
}
return true;
}
And you do not have to do the dirty task of managing the selected item anymore. navigationView manages it by self.
just add this code in onCreate
method:
FragmentTransaction ftrans = getFragmentManager().beginTransaction();
ftrans.replace(R.id.container, <yourfragment>).commit();
Work for me !