3.0之后推荐用actionbar,Menu已经过时但是我们还是了解一下吧,

  • Menu学习
  1. 在java语句中添加menu组件重写onCreateOptionsMenu(Menu menu)方法
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem1 = menu.add(100, 100, 1, "系统菜单");
        menuItem1.setIcon(R.drawable.ic_launcher_background);
        menuItem1.setTitle("菜单一");
        MenuItem menuItem2 = menu.add(100, 101, 2, "系统菜单");
        menuItem2.setIcon(R.drawable.ic_launcher_background);
        menuItem2.setTitle("菜单二");
        MenuItem menuItem3 = menu.add(100, 102, 3, "系统菜单");
        menuItem3.setIcon(R.drawable.ic_launcher_background);
        menuItem3.setTitle("菜单三");

        return super.onCreateOptionsMenu(menu);
    }

当点击具体某个菜单可以调用onOptionsItemSelected(@NonNull MenuItem item) 方法

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case 100:
//                100对应菜单第二个数字id,第三个数字1为顺序,
                Toast.makeText(getApplicationContext(),"你选择了菜单1",Toast.LENGTH_LONG).show();
                break;
            case 101:
                Toast.makeText(getApplicationContext(),"你选择了菜单2",Toast.LENGTH_LONG).show();
                break;
            case 102:
                Intent intent=new Intent();
                intent.setClass(this,Main2Activity.class);

                item.setIntent(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
  1. 在xml文件中添加menu组件
09-20 03:54