系统菜单
首先要在R文件下创建名字menu的文件夹
在menu文件夹中创建menu布局
然后再Activity中重写onCreateOptionsMenu()方法
onOptionsItemSelected()方法是menu的点击事件
//系统菜单
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//获取菜单解析器
MenuInflater menuInflater = getMenuInflater();
//解析menu布局
menuInflater.inflate(R.menu.menu_option,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {//参数为当前点击的菜单选项
Toast.makeText(this, "menu的下标:"+item.getItemId()+"-----标题为:"+item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()){
case R.id.item1:
break;
}
return super.onOptionsItemSelected(item);
}
上下文菜单
哪个控件需要添加上下文,就在初始化控件完后,把空间放到registerForContextMenu()里面
然后再重写onCreateContextMenu()方法
//上下文菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.menu_option,menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
content1.setText(item.getTitle());
return super.onContextItemSelected(item);
}
弹出框菜单
需要自己自定义布局并解析
我这边是封装了一个方法
private void showPopupWindow(){
//需要布局解析器解析自定义布局
View view = LayoutInflater.from(this).inflate(R.layout.pupupwindow_layout_up,null);
PopupWindow popupWindow = new PopupWindow(this);
//将解析好的布局放到弹出菜单中
popupWindow.setContentView(view);
//设置弹出框的高
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//设置弹出框的宽
popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
View parent = LayoutInflater.from(this).inflate(R.layout.activity_popup_window,null);
//设置弹出的位置
popupWindow.showAsDropDown(parent,0,0);
popupWindow.showAtLocation(parent, Gravity.CENTER,0,0);
}