Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish two menu item clicks in ActionBarSherlock?

I have been working with ActionBarSherlock recently, and follwing various tutorials, I wrote this code to add items to Action bar

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    menu.add("Refresh")
        .setIcon(R.drawable.ic_action_refresh)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);


    menu.add("Search")// Search
        .setIcon(R.drawable.ic_action_search)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
}

However, I dont know how to distinguish the two clicks.

Although I did find out that you have to Override onOptionsItemSelected to handle the clicks and also that a switch statement can be used to distinguish between clicks, but most tutorials use item ids from thier xml menus. Since I am not creating menus in xml how can i distinguish the clicks without ids.

like image 718
bakshi_s Avatar asked Jun 01 '12 12:06

bakshi_s


2 Answers

Just check following

http://developer.android.com/guide/topics/ui/actionbar.html

which contains

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {   <--- here you can get it
        case android.R.id.home:
            // app icon in action bar clicked; go home
            Intent intent = new Intent(this, HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
like image 40
Chintan Raghwani Avatar answered Nov 15 '22 09:11

Chintan Raghwani


private static final int REFRESH = 1;
private static final int SEARCH = 2;

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    menu.add(0, REFRESH, 0, "Refresh")
        .setIcon(R.drawable.ic_action_refresh)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);


    menu.add(0, SEARCH, 0, "Search")
        .setIcon(R.drawable.ic_action_search)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case REFRESH:
            // Do refresh
            return true;
        case SEARCH:
            // Do search
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
like image 55
HandlerExploit Avatar answered Nov 15 '22 09:11

HandlerExploit