Aandroid选项菜单实例 二级菜单、静态菜单、动态菜单、菜单动态修改

 switch_menu.xml



    
        
            
            
            
        
    

    

    

MainActivity.java

public class MainActivity extends AppCompatActivity {
    //动态菜单 定义菜单项常量
    final static int MENU_ADD = Menu.FIRST;  //添加
    final static int MENU_SAVE = Menu.FIRST + 1;//保存
    final static int MENU_DELETE = Menu.FIRST + 2;//删除
    final static int MENU_ADDUSER = Menu.FIRST + 3;//添加用户
    final static int MENU_ADDDOCUMENT = Menu.FIRST + 4;//添加文件

    //记录保存状态
    private boolean isSaved=false;//根据该值,动态修改菜单

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        //实例化静态菜单
        MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.switch_menu ,menu);

        //动态添加菜单项
        SubMenu sub = menu.addSubMenu(0, MENU_ADD, 0, "添加").setIcon(R.drawable.a);//一级菜单添加
        //menu.add(0, MENU_ADD, 0, "添加").setIcon(R.drawable.add);
        sub.add(0,MENU_ADDUSER,0,"添加用户").setIcon(R.drawable.a);//二级菜单动态添加
        sub.add(0,MENU_ADDDOCUMENT,1,"添加文档").setIcon(R.drawable.a);

        menu.add(0,MENU_SAVE,2,"保存").setIcon(R.drawable.a);//一级菜单添加
        menu.add(0,MENU_DELETE,1,"删除").setIcon(R.drawable.a);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_ADD:                  //如果是用菜单布局文件写的,应该改为case R.id.menu_add
                Toast.makeText(MainActivity.this, "添加", Toast.LENGTH_SHORT).show();
                break;
            case MENU_SAVE:
                Toast.makeText(MainActivity.this, "保存", Toast.LENGTH_SHORT).show();
                break;
            case MENU_DELETE:
                Toast.makeText(MainActivity.this, "删除", Toast.LENGTH_SHORT).show();
                break;
            case MENU_ADDUSER:
                Toast.makeText(MainActivity.this, "添加用户", Toast.LENGTH_SHORT).show();
                break;
            case MENU_ADDDOCUMENT:
                Toast.makeText(MainActivity.this, "添加文档", Toast.LENGTH_SHORT).show();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    //动态修改菜单项,修改的菜单选项排在最后
    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
        MenuItem item=menu.findItem(MENU_SAVE);
        if (isSaved){
            item.setTitle("保存1");
            item.setEnabled(true);   //设置能否点击
        }
        else{
            item.setTitle("保存2");
            item.setEnabled(true);
        }
        return true;
    }
}

原文地址:Menu控件(Android设置选项菜单和快捷菜单):https://blog.csdn.net/qq_38367681/article/details/84399563

你可能感兴趣的:(android,转载,选项菜单,二级菜单,静态菜单,动态菜单,菜单动态修改)