Clicking app icon doesn't trigger onOptionsItemSelected()

谁说胖子不能爱 提交于 2019-12-31 11:41:40

问题


I'm currently working on an Android app. I would like to use the app icon in the action bar to navigate to the "home" activity. I read on this page that all that needs to be done is to add an onOptionsItemSelected and look for the id android.R.id.home.

This is the code that I have implemented in my activity where I want to press the app icon to return to HomeActivity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
    case android.R.id.home:
        Intent intent = new Intent(this, HomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

However, nothing happens. When debugging, I can see that clicking the icon doesn't trigger the onOptionsItemSelected() at all. Do I have to do something with the icon somewhere? As of now, it's all default, just this in the AndroidManifest.xml

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

回答1:


For packages targetting API level 14 onwards, you need to enable the home button by calling setHomeButtonEnabled()

In your onCreate, add the following:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    getActionBar().setHomeButtonEnabled(true);
}



回答2:


If you use Android new support-actionbar (AppCompat) you need to make both calls.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    getActionBar().setHomeButtonEnabled(true);
}
getSupportActionBar().setHomeButtonEnabled(true);



回答3:


i dont know if we have the same problem.

but, i was on that problem and now solved..

do you add

case android.R.id.home:
    Intent intent = new Intent(this, HomeActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    return true;

in HomeActivity ? this is false..

you should put that code on your secondActivity.. because your home button on secondActivity, not HomeActivity

case android.R.id.home:
     NavUtils.navigateUpFromSameTask(this);
     true;

hope this helps you



来源:https://stackoverflow.com/questions/8953120/clicking-app-icon-doesnt-trigger-onoptionsitemselected

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