Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android PopupMenu setGravity (API < 19)

Tags:

android

menu

In Android API 19 was added contructor of PopupMenu which allows specify gravity.

public PopupMenu (Context context, View anchor, int gravity)

How i can set gravity in older versions?

like image 449
Sergey Shustikov Avatar asked Nov 14 '14 11:11

Sergey Shustikov


People also ask

How do I open the pop up menu on Android?

Go to app > res > right-click > New > Android Resource Directory and give Directory name and Resource type as menu. Now, we will create a popup_menu file inside that menu resource directory. Go to app > res > menu > right-click > New > Menu Resource File and create a menu resource file and name it as popup_menu.

What is popup menu in Android user interface?

Android Popup Menu displays a list of items in a vertical list which presents the view that invoked the menu and is useful to provide an overflow of actions related to specific content.


2 Answers

Change line import android.widget.PopupMenu; to import android.support.v7.widget.PopupMenu;

like image 79
VIktor Isakov Avatar answered Sep 27 '22 17:09

VIktor Isakov


you can use rtl for giving gravity to right here is link

RTL was started to support at Android 4.2

or you can create a custom popupmenu and inflate it.

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            popup = new PopupMenu(context, arg1,Gravity.CENTER );
            //popupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);     
        }
        //Inflating the Popup using xml file  
        popup.getMenuInflater().inflate(R.menu.listmenu, popup.getMenu());

or you can give anchor and style

showPopup(viewOfWherePopupmenuShows,popmenuNameList.size());


PopupMenu popMenu = new PopupMenu(Activity.this,v)
int size =popmenuNameList.size();
for(int i =0; i <size; i++){
 popMenu.getMenu().add(popmenuNameList.get(i)).setIcon(R.drawable.logo);

}
 popMenu.show();

protected void showPopupMenu(View v, int size){
   //create instance
   PopupMenu popup = new PopupMenu(Activity.this,v);
   //inflating the popup using xml
   popup.getMenuInflater().inflate(R.menu.menu_popup_list),popup.getMenu());
}

The style of menu is determined by the style of context you pass. So all you need to do is to pass your Activity reference as context

style here;

 <style name="style" parent="android:Theme.Holo.Light">

    <item name="android:popupMenuStyle">...</item>
    <item name="android:popupAnimationStyle">...</item>
   <item name="android:popupBackground">...</item>

</style>
like image 43
Alp Avatar answered Sep 27 '22 19:09

Alp