Android Change Navigation Drawer Menu Items Text programmatically

前端 未结 5 1388
暗喜
暗喜 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:22

    This code can be used to add menus dynamically. it worked for me... the main part of the code is the displayItems();.....pass the String[] of items as a parameter to the function....it works.

    public class Courses extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    
        TextView nn,ne,np,nl;
        SharedPreferences sp;
        NavigationView navigationView;
        DrawerLayout drawer;
        ImageView img;
        NavigationView nv;
        int id;
    
    String[] acc={"ACPFAT","CPFA","Tally.ERP 9 Simplified","D P F A","CA Articles","DAA","TFAP","Tally.ERP 9 - Specialization","GST (Goods and service Tax)"};
    
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.setDrawerTitle(Gravity.CENTER,n);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, 
                     R.string.navigation_drawer_open,R.string.navigation_drawer_close);
    
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    navigationView.setNavigationItemSelectedListener(this);
    
    Intent i=getIntent();
    id=i.getIntExtra("button",0);
    
    switch(id)
        {
    
            case R.id.account:
                img.setImageResource(R.drawable.acc);
                displayItems(acc);
                break;
    
            case R.id.modular:
                img.setImageResource(R.drawable.acc);
                displayItems(mod);
                break;
    
            case R.id.diploma:
    
                img.setImageResource(R.drawable.acc);
                displayItems(dc);
                break;
    
        }
    
    public void displayItems(String[] a)
      {
    
        final NavigationView navigationView=findViewById(R.id.nav_view);
        final DrawerLayout drawer=findViewById(R.id.drawer_layout);
        Menu menu=navigationView.getMenu();
        SubMenu sb=menu.addSubMenu("Courses");
    
        int i=0;
        while(i

提交回复
热议问题