How to add menu button without action bar?
You can simply use PopupMenu
, for example add the following to a button when clicked:
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.actions, popup.getMenu());
popup.show();
}
Kotlin
fun showPopup(v : View){
val popup = PopupMenu(this, v)
val inflater: MenuInflater = popup.menuInflater
inflater.inflate(R.menu.actions, popup.menu)
popup.setOnMenuItemClickListener { menuItem ->
when(menuItem.itemId){
R.id.action1-> {
}
R.id.action2-> {
}
}
true
}
popup.show()
}
For more info, read Creating a Popup Menu
:
http://developer.android.com/guide/topics/ui/menus.html
Add a toolbar the layout and make it transparent. That is the best solution to adding menu items to a layout while giving the appearance there is no actionbar/toolbar.
Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The rest of your code here -->
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="@android:color/transparent"/>
</RelativeLayout>
Theme
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
</resources>
Example of inflating the menu, setting title, menu click listener.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Toolbar");
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
}
return false;
}
});
Don't set the Toolbar as the action bar. The theme just removes it totally.
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_overflow_holo_dark"
android:contentDescription="@string/descr_overflow_button"
android:onClick="showPopup" />
Add above lines in xml file where you want to show this menu.
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
// This activity implements OnMenuItemClickListener
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.actions);
popup.show();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.archive:
archive(item);
return true;
case R.id.delete:
delete(item);
return true;
default:
return false;
}
}
For more details go through: https://developer.android.com/guide/topics/ui/menus.html