Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save MohammadSamandari/14ec14011e60eeba9904d38c629d818b to your computer and use it in GitHub Desktop.

Select an option

Save MohammadSamandari/14ec14011e60eeba9904d38c629d818b to your computer and use it in GitHub Desktop.
Adding Menu to the activity, customising the action bar
// For Creating a menu in android, we need to add a new file. and we need to customise
// MainActivity.java file.
// The new file is a xml layout file which only gives the layout for our menu
// We created a folder in res as menu an inside that created a menu resource file.
// We customise the xml file and added items for the menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/settings"
android:title="Setting"/>
<item
android:id="@+id/help"
android:title="Help"/>
</menu>
// We should add this override.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// what we mainly want to do is linking this options Menu with the xml file that
// we just created.
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
// now the menu will appear. but it will do nothing. so we add
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// we are going to check which item is sellected. we use a switch.
// switch is like a big if else statement.
switch (item.getItemId()) {
case R.id.settings:
Log.i("Lord-Menu", "Settings");
return true;
case R.id.help:
Log.i("Lord-Menu", "Help");
return true;
default:
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment