Options Menu

We add an Options Menue to the app as described here.

For all menu types, Android provides a standard XML format to define menu items. Instead of building a menu in your activity's code, you should define a menu and all its items in an XML menu resource. (Source)

Create new ressource file

Right click /res and select New -> Android Ressource Direcroty. Leave Directory Name unchanged, choose resource type menu and click ok.

Add a new Menu Ressource File and name the file menu_main.xml. We choose a very simple menu structure:

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/mainMenuPost"
        android:icon="?android:attr/actionModeShareDrawable"
        android:title="Post"
        app:showAsAction="always" />

    <item
        android:id="@+id/mainMenuManageAccount"
        android:title="Post"
         />


    <item
        android:id="@+id/mainMenuHelp"
        android:title="@string/help"
        />

    <item
        android:id="@+id/mainMenuTest"
        android:title="Test"
        />

    <item
        android:id="@+id/idWriteTime"
        android:title="Write Time"
        />
</menu>

Now update your string ressurces with string literals needed.

Create UI Options Menu

Add the following call to ActivityMain.java. Note that we see the R file in action for the first time. AS autmaticall created an identifier to get access to our file menu_main.xml

  @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }

Test. Your app should show the menu after clicking on the three dots.

We need to add some logic now.

Add logic to menu calls

Add the following call to ActivityMain.java. Note, how we use the class Rto access the elements of menu_main.xml and detect, what entry was selected.

     @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.mainMenuPost:
                Log.d(TAG, "Post was pressed");                
                return true;

            case R.id.mainMenuHelp:
                Log.d(TAG, "Help was pressed");
                return true;

            case R.id.mainMenuTest:
                Log.d(TAG, "Test was pressed");
                return true;

            case R.id.mainMenuManageAccount:
                Log.d(TAG, "ManageAccount was pressed.");
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

Test and try to spot the log messages in logcat. (Do not forget to declare TAG!)

The log message in logcat:

results matching ""

    No results matching ""