I want use ToolBar
instead of ActionBar
, but don\'t show me menu in toolbar!!! i want set menu such as Refresh or Setting<
Although I agree with this answer, as it has fewer lines of code and that it works:
How to set menu to Toolbar in Android
My suggestion would be to always start any project using the Android Studio Wizard. In that code you will find some styles:-
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
and usage is:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
Due to no action bar theme
declared in styles.xml
, that is applied to the Main Activity
in the AndroidManifest.xml
, there are no exceptions, so you have to check it there.
<activity android:name=".MainActivity" android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Toolbar
is not an independent entity, it is always a child
view in AppBarLayout
that again is the child of
CoordinatorLayout
.BOTH:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
AND:
How to set menu to Toolbar in Android
WILL WORK.
Happy Coding :-)
Here is a fuller answer as a reference to future visitors. I usually use a support toolbar but it works just as well either way.
This is going to be in res/menu/main_menu
.
res
folder and choose New > Android Resource File.main_menu
for the File name.Paste in the following content as a starter.
<?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:id="@+id/action_add"
android:icon="@drawable/ic_add"
app:showAsAction="ifRoom"
android:title="Add">
</item>
<item
android:id="@+id/action_settings"
app:showAsAction="never"
android:title="Settings">
</item>
</menu>
You can right click res
and choose New image asset to create the ic_add
icon.
In your activity add the following method.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
Also in your Activity, add the following method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_add:
addSomething();
return true;
case R.id.action_settings:
startSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}