Modify from last example of "Set title, subtitle and logo of Toolbar", to add OptionsMenu to Toolbar.
Create /res/menu/menu_main.xml to define our OptionsMenu.
<?xml version="1.0" encoding="utf-8"?>
<menu
>
<item
android_id="@+id/menu_camera"
android_icon="@android:drawable/ic_menu_camera"
android_orderInCategory="100"
android_title="camera"
app_showAsAction="always"/>
<item
android_id="@+id/menu_compass"
android_icon="@android:drawable/ic_menu_compass"
android_orderInCategory="100"
android_title="compass"
app_showAsAction="always"/>
<item
android_id="@+id/menu_agenda"
android_icon="@android:drawable/ic_menu_agenda"
android_orderInCategory="100"
android_title="agenda"
app_showAsAction="always"/>
<item
android_id="@+id/menu_gallery"
android_icon="@android:drawable/ic_menu_gallery"
android_orderInCategory="100"
android_title="gallery"
app_showAsAction="always"/>
<item
android_id="@+id/menu_calendar"
android_icon="@android:drawable/ic_menu_my_calendar"
android_orderInCategory="100"
android_title="calendar"
app_showAsAction="always"/>
</menu>
Modify MainActivity.java, override onCreateOptionsMenu() and onOptionsItemSelected().
package com.blogspot.android_er.androidtoolbar;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Toolbar example");
toolbar.setSubtitle("Android-er.blogspot.com");
toolbar.setLogo(android.R.drawable.ic_menu_info_details);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, item.getTitle(), Toast.LENGTH_LONG).show();
return super.onOptionsItemSelected(item);
}
}
Next:
- Set image on Toolbar
0 comments:
Post a Comment