创建menu
资源文件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/one"
android:title="@string/menu"
/>
</menu>
Activity添加点击事件,创建PopupMenu
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_root_v2);
View menuImageButton = findViewById(R.id.menuImageButton);
menuImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showPopupMenu(view);
}
});
}
private void showPopupMenu(View view) {
PopupMenu popup = new PopupMenu(RootActivityV2.this, view);
popup.getMenuInflater().inflate(R.menu.activity_root, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()){
...
}
return true;
}
});
popup.show();
}