Creating menu bar on Android
onCreateOptionsMenu()
method should be override.The
showAsAction
attribute allows you to define how the action is displayed. For example, the ifRoom
attribute defines that the action is only displayed in the action bar if there is sufficient screen space available.<?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_settings"
android:title="@string/menu_title"
app:showAsAction="never"
android:orderInCategory="100"/>
</menu>
The
MenuInflator
class allows to inflate actions defined in an XML file and adds them to the action bar. MenuInflator
can get accessed via the getMenuInflator()
method from your activity. The following example code demonstrates the creation of actions.@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
While you can define the actions also in your source code, it is good practice to do this via XML files, as this results in less boilerplate code. |