Create pop-up menu in Sketchware

In order to display a pop-up menu on button click or on ListView item click in your Sketchware project, use the codes provided below.

PopupMenu on button click

1. To display a PopupMenu when a Button is clicked, in onButtonClick event, use add source directly block, and put following code in it:
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
Menu menu = popup.getMenu();
menu.add("Delete");
menu.add("Show");

This code creates a PopupMenu for button1, with two options Delete and Show.

The same code can be used for creating PopupMenu for ImageView, TextView or or any other widget by using their id in place of button1.

2. After this add another​ add source directly block and put following code in it:
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
@Override
public boolean onMenuItemClick(MenuItem item){
switch (item.getTitle().toString()){
case "Delete":

This code sets OnMenuItemClickListener for the PopupMenu. Since the menu has two items Delete, and Show, we create a switch which detects the Title of item clicked. Then we set the case when Delete is clicked.

3. Add blocks which will be executed when the option "Delete" in PopupMenu is clicked.

4. Add another add source directly block and put following code in it:
break;
case "Show":

5. Add blocks which will be executed when the option "Show" in PopupMenu is clicked.
In image above Toast Block is used.

6. Add another add source directly block and put following code in it:
break;}
return true;
}
});
popup.show();

PopupMenu on ListView item click

For displaying a PopupMenu on ListView item click, use the same code as above. Just replace the id of view 'button1' with _view. The code will look like this:
PopupMenu popup = new PopupMenu(MainActivity.this, _view);
Menu menu = popup.getMenu();
menu.add("Delete");
menu.add("Show");

No comments:

Post a Comment