How to select the first item in a navigation drawer and open a fragment on application start

前端 未结 8 506
鱼传尺愫
鱼传尺愫 2021-02-04 05:32

I have created MainActivity with NavigationView. When Activity is opened I want to automatically select the first item in the navigation d

相关标签:
8条回答
  • 2021-02-04 06:23

    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.

    0 讨论(0)
  • 2021-02-04 06:31

    just add this code in onCreate method:

    FragmentTransaction ftrans = getFragmentManager().beginTransaction();
    ftrans.replace(R.id.container, <yourfragment>).commit();
    

    Work for me !

    0 讨论(0)
提交回复
热议问题