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

前端 未结 8 607
鱼传尺愫
鱼传尺愫 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条回答
  •  Happy的楠姐
    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.

    
    
        
            
        
    

    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.

提交回复
热议问题