I want to customize the popupmenu
in android, default popup menu gives more space ,so I\'m trying to change the custom layout in popup menu but I cant figure ou
To inflate popupMenu
from a button onClick
, use the following code.
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.this, v);
popup.getMenuInflater().inflate(R.menu.pop_up, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this, "Some Text" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();//showing popup menu
}
});
EDIT
To style the popupMenu, add the following style.
I noticed you also want to add icons next to your text. It is possible to add icons in popupMenu. However it is a better approach to use popup Window instead. Here is a sample code:
PopupWindow mypopupWindow;
setPopUpWindow();
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mypopupWindow.showAsDropDown(v,-153,0);
//showAsDropDown(below which view you want to show as dropdown,horizontal position, vertical position)
}
}
});
}
private void setPopUpWindow() {
LayoutInflater inflater = (LayoutInflater)
getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.popup, null);
Start=(RelativeLayout)view.findViewById(R.id.start_btn);
Pause=(RelativeLayout)view.findViewById(R.id.pause_btn);
Stop=(RelativeLayout)view.findViewById(R.id.stop_btn);
mypopupWindow = new PopupWindow(view,300, RelativeLayout.LayoutParams.WRAP_CONTENT, true);
popup Layout
The whitedrawable
can be used to set a background of your choice. You can use 9patch to get the shadow and rounded corners for the background.
To dismiss the popupWindow, use the following code:
mypopupWindow.getContentView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mypopupWindow.dismiss();
}
});
To dismiss using the back button, use:
@Override
public void onBackPressed() {
if(mypopupWindow.isShowing()) {
mypopupWindow.dismiss();
return;
}
super.onBackPressed();
}