简介:
SubMenu:代表一个子菜单,包含1~N个MenuItem
实现效果:
具体实现方法:
主活动 MainActivity:
代码语言:javascript复制public class MainActivity extends AppCompatActivity {
//定义 “字体大小” 菜单项的标识
final int FONT_10 = 0x111;
final int FONT_12 = 0x112;
final int FONT_14 = 0x113;
final int FONT_16 = 0x114;
final int FONT_18 = 0x115;
//定义“普通菜单项” 的标识
final int PLAIN_ITEM = 0x11b;
//定义“字体颜色”的菜单项的标识
final int FONT_RED = 0x116;
final int FONT_BLUE = 0x117;
final int FONT_GREEN = 0x118;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.txt);
}
//当用户点击按钮键时 触发该方法
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//添加字体大小的子菜单
SubMenu fontMenu = menu.addSubMenu("字体大小");
//设置菜单图标
fontMenu.setIcon(R.drawable.seek02);
//设置菜单头的图标
fontMenu.setHeaderIcon(R.drawable.seek03);
//设置菜单头的标题
fontMenu.setHeaderTitle("选择字体大小");
fontMenu.add(0, FONT_10, 0 ,"10号字体");
fontMenu.add(0, FONT_12, 0 ,"12号字体");
fontMenu.add(0, FONT_14, 0 ,"14号字体");
fontMenu.add(0, FONT_16, 0 ,"16号字体");
fontMenu.add(0, FONT_18, 0 ,"18号字体");
//向Menu中添加普通菜单项
menu.add(0, PLAIN_ITEM, 0, "普通菜单选项");
//向Menu中添加"字体颜色"的子菜单
SubMenu colorMenu = menu.addSubMenu("字体颜色");
colorMenu.setIcon(R.drawable.find1);
//设置菜单头图标
colorMenu.setHeaderIcon(R.drawable.find);
//设置菜单头标题
colorMenu.setHeaderTitle("选择文字颜色");
colorMenu.add(0, FONT_RED, 0, "红色");
colorMenu.add(0, FONT_GREEN, 0, "绿色");
colorMenu.add(0, FONT_BLUE, 0, "蓝色");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//判断单机的是那个菜单项
switch (item.getItemId()){
case FONT_10:
editText.setTextSize(10*2);
break;
case FONT_12:
editText.setTextSize(12*2);
break;
case FONT_14:
editText.setTextSize(14*2);
break;
case FONT_16:
editText.setTextSize(16*2);
break;
case FONT_18:
editText.setTextSize(18*2);
break;
case FONT_RED:
editText.setTextColor(Color.RED);
break;
case FONT_GREEN:
editText.setTextColor(Color.GREEN);
break;
case FONT_BLUE:
editText.setTextColor(Color.BLUE);
break;
case PLAIN_ITEM:
Toast.makeText(MainActivity.this,"you click menu",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
布局中添加 EditText:
代码语言:javascript复制