Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement pop up Menu with margin

Tags:

I am using the default pop menu and expecting the behavior of the same. Everything is working fine. What my concern is regarding the rendering of pop up menu. My pop up menu sticks to the right of the screen.

I want the behavior as used by Youtube app for android.enter image description here

I am mainly not able to provide right margin to my pop up menu. Please help. I have tried providing Gravity to PopUp Menu. But Pop Up Menu sticks to the Right of screen.

PopupMenu popupMenu = new PopupMenu(mContext, anchor, Gravity.LEFT); popupMenu.getMenuInflater().inflate(R.menu.menu_edit_accessory, popupMenu.getMenu()); 
like image 474
Anchit Mittal Avatar asked Dec 24 '15 07:12

Anchit Mittal


People also ask

How do I create a popup menu?

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 are the two types of popup menu?

There are three types of menus in Android: Popup, Contextual and Options. Each one has a specific use case and code that goes along with it.

What displays a pop up menu?

A PopupMenu displays a Menu in a modal popup window anchored to a View . The popup will appear below the anchor view if there is room, or above it if there is not. If the IME is visible the popup will not overlap it until it is touched. Touching outside of the popup will dismiss it.


1 Answers

You can change your PopupMenu's position by using the following attributes: gravity, dropDownHorizontalOffset and dropDownVerticalOffset

First set gravity to Gravity.END

popup.setGravity(Gravity.END); 

Then change your dropdown-offsets by creating a style

<style name="MyPopupMenu" parent="@style/Widget.AppCompat.PopupMenu">     <item name="android:dropDownHorizontalOffset">-4dp</item>     <item name="android:dropDownVerticalOffset">4dp</item> </style> 

If you want to overlap the anchor view use

parent="@style/Widget.AppCompat.PopupMenu.Overflow" 

Lastly apply MyPopupMenu to your theme

<item name="popupMenuStyle">@style/MyPopupMenu</item> 
like image 119
Markus Rubey Avatar answered Oct 15 '22 21:10

Markus Rubey