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

一世执手 提交于 2019-12-13 12:08:30

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18586300/how-to-find-out-the-string-id-of-an-item-in-the-menu-knowing-its-decimal-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!