Android Change Navigation Drawer Menu Items Text programmatically

前端 未结 5 1546
暗喜
暗喜 2021-01-30 20:33

I have the new Navigation Drawer in my app and I want to change the navigation view menu items title text dynamically from code. I have watched many posts but I can\'t figure ou

5条回答
  •  情书的邮戳
    2021-01-30 21:23

    You can change the title of Navigation Menu Item programmatically by adding following lines in MainActivity.java file.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...
        //other stuff here
        ...
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    
        // get menu from navigationView
        Menu menu = navigationView.getMenu();
    
        // find MenuItem you want to change
        MenuItem nav_camara = menu.findItem(R.id.nav_camara);
    
        // set new title to the MenuItem
        nav_camara.setTitle("NewTitleForCamera");
    
        // do the same for other MenuItems
        MenuItem nav_gallery = menu.findItem(R.id.nav_gallery);
        nav_gallery.setTitle("NewTitleForGallery");
    
        // add NavigationItemSelectedListener to check the navigation clicks
        navigationView.setNavigationItemSelectedListener(this);
    
    }
    

    This works fine for me. Hope it'll help you.

提交回复
热议问题