【Android笔记】SubMenu子菜单

原创
2016/10/01 19:40
阅读数 178
package com.example.demo17;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    /**
     * 添加菜单
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu file = menu.addSubMenu("文件");
        SubMenu setting = menu.addSubMenu("设置");

        file.setHeaderTitle("文件操作");
        file.setIcon(R.drawable.book);
        file.add(1, 100, 1, "复制");
        file.add(1, 101, 1, "剪切");
        file.add(1, 102, 1, "粘贴");
        setting.setHeaderTitle("用户设置");
        setting.setIcon(R.drawable.baidu);
        setting.add(2, 103, 1, "亮度");
        setting.add(2, 104, 1, "音量");
        setting.add(2, 105, 1, "震动");

        return true;
    }

    /**
     * 菜单事件监听
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getGroupId() == 1) {
            switch (item.getItemId()){
                case 100:
                    Toast.makeText(MainActivity.this, "复制", Toast.LENGTH_SHORT).show();
                    break;
                case 101:
                    Toast.makeText(MainActivity.this, "剪切", Toast.LENGTH_SHORT).show();
                    break;
                case 102:
                    Toast.makeText(MainActivity.this, "粘贴", Toast.LENGTH_SHORT).show();
                    break;
            }
        } else if(item.getGroupId() == 2) {
            switch (item.getItemId()){
                case 103:
                    Toast.makeText(MainActivity.this, "亮度", Toast.LENGTH_SHORT).show();
                    break;
                case 104:
                    Toast.makeText(MainActivity.this, "音量", Toast.LENGTH_SHORT).show();
                    break;
                case 105:
                    Toast.makeText(MainActivity.this, "震动", Toast.LENGTH_SHORT).show();
                    break;
            }
        }

        return super.onOptionsItemSelected(item);
    }
}

运行效果

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部