This is a little late but I hope this helps someone.
I was trying to do what you were doing with a PopupMenu
but nothing was working for me until I learned about ListPopupWindow
. It's a way better alternative. Much more flexible in my opinion and you can achieve the margin-spacing you were asking about.
Here's the code:
public class MainActivity extends AppCompatActivity
{
private ImageButton mMoreOptionsButton;
private ArrayAdapter<String> mPopupAdapter;
private ArrayList<String> mOptionsArray =
new ArrayList<>(Arrays.asList("Option1", "Option2", "Option3"));
private ListPopupWindow mPopupWindow;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMoreOptionsButton = (ImageButton) view.findViewById(R.id.more_options_button);
setupPopupWindow();
}
private void setupPopupWindow()
{
mPopupAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, mOptionsArray);
mPopupWindow = new ListPopupWindow(MainActivity.this);
mPopupWindow.setAdapter(mPopupAdapter);
mPopupWindow.setAnchorView(mMoreOptionsButton);
mPopupWindow.setWidth(500);
mPopupWindow.setHorizontalOffset(-380); //<--this provides the margin you need
//if you need a custom background color for the popup window, use this line:
mPopupWindow.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(MainActivity.this, R.color.gray)));
mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//do something with item by referring to it using the "position" parameter
}
});
mMoreOptionsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
mPopupWindow.show();
}
});
}
}
The key part is calling mPopupWindow.setHorizontalOffset()
. Be aware that this method is tricky. Depending on the value you set in mPopupWindow.setWidth()
you will have to adjust the value in setHorizontalOffset()
accordingly. It just so happened that for my app, -380
was the perfect amount of margin I needed from the end. So you may have to play with this value a bit.
I believe the same can be said for using setHeight()
and setVerticalOffset()
if you want some margin at the top of your popup window.
Hope this helps :]