Reputation: 141
I want to create a pop menu for context menu, so that when I long press the context menu, it shows another pop up menu.
This is the code I've written for context menu
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.btn)
registerForContextMenu(button)
}
override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
menu?.setHeaderTitle("Choose one")
menu?.add(0, v?.getId()!!, 0, "Upload")
menu?.add(0, v?.getId()!!, 0, "Search")
menu?.add(0, v?.getId()!!, 0, "Share")
}
override fun onContextItemSelected(item: MenuItem): Boolean {
return super.onContextItemSelected(item)
}
Upvotes: 2
Views: 1207
Reputation: 579
In Java when i long press the button it shows context menu, then i select context menu it shows popup menu.
Button button = findViewById(R.id.button);
registerForContextMenu(button);
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Upload");
menu.add(0, v.getId(), 0, "Search");
menu.add(0, v.getId(), 0, "Share");
menu.add(0, v.getId(), 0, "Bookmark");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
try {
showPopup(findViewById(item.getItemId()));
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
private void showPopup(View anchorView) {
PopupMenu popup = new PopupMenu(this, anchorView);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MapsActivity.this, "Selected Item: "
+ item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popup.inflate(R.menu.menu_example);
popup.show();
}
Upvotes: 1
Reputation: 25
You may want to add SubMenu objects to your menu with the addSubMenu() method. Here's the reference for creating menus if you want to go more into menu creating stuff.
Upvotes: 0