java - How to show a popup menu when clicked on a menu item in android -
i trying show popup menu when clicked on menu item. i'm getting error "menupopuphelper cannot used without anchor". can .i know i'm missing something.i searched in internet solve error nothing helped.
my menu_main.xml file
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:title="screen1" android:id="@+id/scr1"/> <item android:title="screen2" android:id="@+id/scr2"/> <item android:title="screen3" android:id="@+id/scr3" /> <item android:title="change sound" android:id="@+id/changesound" /> </menu>
popup_menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:title="female" android:id="@+id/voice_female" /> <item android:title="male" android:id="@+id/voice_male" /> </menu>
and activity code
public class main3activity extends appcompatactivity { button btn_default; string username; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); btn_default=(button)findviewbyid(r.id.setdefault); //set button click btn_default.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { ; } }); } @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.menu_main,menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()){ case r.id.scr1: break; case r.id.scr2: break; case r.id.scr3: break; case r.id.changesound: showpopup(); break; } return super.onoptionsitemselected(item); } public void showpopup() { view v=findviewbyid(r.id.changesound); //creating instance of popupmenu popupmenu popup = new popupmenu(main3activity.this, v); //inflating popup using xml file popup.getmenuinflater().inflate(r.menu.popup_menu, popup.getmenu()); //registering popup onmenuitemclicklistener popup.setonmenuitemclicklistener(new popupmenu.onmenuitemclicklistener() { public boolean onmenuitemclick(menuitem item) { toast.maketext(main3activity.this, "clicked", toast.length_short).show(); return true; } }); popup.show();//showing popup menu } }
check if using support popupmenu.
import android.support.v7.widget.popupmenu;
i had same problem using activity , support instead of activity ,
import android.widget.popupmenu;
wish helps you.
Comments
Post a Comment