开发者

Is using menuItem.getItemId() valid in finding which MenuItem is selected by user?

I have menu in my App. I need to check for the which menu item been selected by the user and take appropriate action. I did this as,

    @Override
public boolean onOptionsItemSelected(MenuItem menuitem){
        String title = menuitem.getTitle().toString();
        int itemId = menuitem.getItemId();
                    switch(itemId){
                     开发者_开发技巧   case 2131296257:
                                -----------------;
                                break;
                        case 2131296258:
                                 ------------------;
                                 break;                             
                    }

But these MenuItem Id's are getting changed each time I run my App. Now I thought to compare the menuTitle with hard coded string values like ,

 String title = menuitem.getTitle().toString();

   if(title.equals("Settings..")){
                ------------- 
                ------------- 
                -------------
   } 

But I don't think it's a good practice. But I guess I can do the same using the menu titles defined in strings.xml. But I am not sure how to use this.... (like R.string.....).

Can someone suggest on this please.

Thanks


Here's an example menu named game_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"
          android:icon="@drawable/ic_new_game"
          android:title="@string/new_game" />
    <item android:id="@+id/help"
          android:icon="@drawable/ic_help"
          android:title="@string/help" />
</menu>

Inflating a Menu Resource

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

Responding to user action

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.new_game:
        newGame();
        return true;
    case R.id.help:
        showHelp();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

for more information click here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜