开发者

Android: show menu options on an Activity with Tabs

开发者 https://www.devze.com 2023-04-11 23:48 出处:网络
I want to show menu options in an activity which hosts tab views. Here is the code of my tab view activity.

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.


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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号