Reputation: 147
I'm trying to create a Toolbar with the android.support.v7.widget.toolbar but when i try t add an item, it will not show on the toolbar:
Toolbar in activity_main.xml:
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
main_activity: on the onCreate:
Toolbar my_tbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(my_tbar);
out of onCreate:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
res/menu/main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:title="RefreshButton"
android:id="@+id/refresh"
android:icon="@drawable/refresh_icon"
app:showAsAction="always"
/>
</menu>
the refresh_icon
is created by me because in the @drawable/
i didn't found the ic_menu_refresh
Why the button is not shown?
Thank you
Upvotes: 2
Views: 1323
Reputation: 14835
It is not showing because your not infalting the menu layout. Before calling onOptionsItemSelected()
you need to inflate the layout like this
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
just add this method in your activity, and it will work fine.
Upvotes: 3