Android support:design NavigationView checked menu sub items

后端 未结 4 1390
无人及你
无人及你 2021-01-18 08:25

I have recently started converting my android app to use the latest support library called support:design.

While implementing the new NavigationView i\'ve stumbled u

4条回答
  •  走了就别回头了
    2021-01-18 08:55

    I resolved this recurrent problem in this way that works very well.

    We must simply memorize the id of the selected item, recharge your menu on your NavigationView and select the item again.

    For that you need to have your menu drawer like way :

    
    
        
    
            
                
                    
    
                    
                    ...
                
            
        
            ...
        
    
            
                
                    
    
                    
                    ...
                
            
        
    
    

    So, my solution :

    public class YourActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    
    ...
    private NavigationView mNavigationView;
    private int mNavItemId;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    
        // load saved navigation state if present
        if (null == savedInstanceState) {
            mNavItemId = R.id.item_1_section_1;
        } else {
            mNavItemId = savedInstanceState.getInt(NAV_ITEM_ID);
        }
    
        // listen for navigation events
        mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
        mNavigationView.setNavigationItemSelectedListener(this);
    
        // select the correct nav menu item
        mNavigationView.getMenu().findItem(mNavItemId).setChecked(true);
    }
    
    @Override
    public boolean onNavigationItemSelected(final MenuItem menuItem) {
        // update highlighted item in the navigation menu
        mNavItemId = menuItem.getItemId();
    
        // allow some time after closing the drawer before performing real navigation
        // so the user can see what is happening
        mDrawerLayout.closeDrawer(GravityCompat.START);
        mDrawerActionHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ...
            }
        }, DRAWER_CLOSE_DELAY_MS);
    
        // Reload menuDrawer to keep selected item
        mNavigationView.getMenu().clear();
        mNavigationView.inflateMenu(R.menu.menu_drawer);
        mNavigationView.getMenu().findItem(mNavItemId).setChecked(true);
    
        return true;
    }
    
    ...
    
    }
    

提交回复
热议问题