Saturday, October 17, 2015

Android example to create grouped sub-OptionsMenu


Create menu/activity_main.xml
<?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/option1"
        android:orderInCategory="100"
        app:showAsAction="ifRoom"
        android:title="Option 1"/>
    <item
        android:id="@+id/option2"
        android:orderInCategory="100"
        app:showAsAction="never"
        android:title="Option 2"/>
    <item
        android:id="@+id/option3"
        android:orderInCategory="100"
        app:showAsAction="never"
        android:title="Option 3...">
        <menu >
            <group android:id="@+id/group3"
                android:checkableBehavior="single">
                <item android:id="@+id/submenu3a"
                    android:title="SubMenu 3A" />
                <item android:id="@+id/submenu3b"
                    android:title="SubMenu 3B" />
            </group>
        </menu>

    </item>
</menu>

MainActivity.java
package com.blogspot.android_er.androidoptionsmenu;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case R.id.option1:
                Toast.makeText(MainActivity.this, "Option 1", Toast.LENGTH_LONG).show();
                return true;
            case R.id.option2:
                Toast.makeText(MainActivity.this, "Option 2", Toast.LENGTH_LONG).show();
                return true;
            case R.id.submenu3a:
                Toast.makeText(MainActivity.this, "Option 3 A", Toast.LENGTH_LONG).show();
                return true;
            case R.id.submenu3b:
                Toast.makeText(MainActivity.this, "Option 3 B", Toast.LENGTH_LONG).show();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}



1 comment:

Unknown said...

tnx for great post, it saved me lot of time with my own tries ;]