Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out the String ID of an item in the Menu knowing its decimal value?

I am using android-support-v7-appcompat.

In an activity I want to show in the actionbar the back button. I do:

    public class News extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_news_screen);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
       }
}

And:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        System.out.println(item.getItemId()); // 16908332
        System.out.println(R.id.home); // 2131034132
        System.out.println(R.id.homeAsUp); // 2131034117
        switch(item.getItemId())
        {
            case R.id.home:
                onBackPressed();
                break;
            case R.id.homeAsUp:
                onBackPressed();
                break;              
            case 16908332:
                onBackPressed(); // it's works
                break;              
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }

If I use numerical filter by id works, but I think that ID is generated by R and therefore can change, is therefore used R.id. . Any idea?

like image 949
ephramd Avatar asked Sep 03 '13 07:09

ephramd


1 Answers

The home/back icon in the actionbar has the id android.R.id.home. You can look for that id.

The values in android.R.* will never change and are linked statically.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.home:
            onBackPressed();
            break;
        case R.id.homeAsUp:
            onBackPressed();
            break;              
        case android.R.id.home:
            onBackPressed();
            break;              
        default:
            return super.onOptionsItemSelected(item);
    }
    return true;
}
like image 154
flx Avatar answered Nov 20 '22 01:11

flx