Android: show menu options on an Activity with Tabs

1.4k Views Asked by At

I want to show menu options in an activity which hosts tab views. Here is the code of my tab view activity.

public class Tabs3 extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final TabHost tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("list")
                .setContent(new Intent(this, List1.class)));

        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("photo list")
                .setContent(new Intent(this, List8.class)));
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.removeGroup(0);

        menu.add(0, 0, 0, "Home").setIcon(
                android.R.drawable.ic_menu_preferences);

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case 0:
            setResult(10);
            finish();
            return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }
}

Now when i am pressing android menu button, onPrepareOptionsMenu is called which is correct but when i select the menu option, nothing happens. I have also debugged my code and control is not reaching in onMenuItemSelected.

Please help.

1

There are 1 best solutions below

0
On

I got my solution.. i dont whether it is perfect way to do it but it is working..

instead of using onMenuItemSelected , i just used onOptionsItemSelected and my code is working.

Here is the final code:

public class Tabs3 extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final TabHost tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("list")
                .setContent(new Intent(this, List1.class)));

        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("photo list")
                .setContent(new Intent(this, List8.class)));
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.removeGroup(0);

        menu.add(0, 0, 0, "Home").setIcon(
                android.R.drawable.ic_menu_preferences);

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 0:
            setResult(10);
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}