Enable home button ActionbarSherlock, Sherlockfragment

岁酱吖の 提交于 2019-12-01 18:03:05

Have you tried adding the below code the main Activity - the one that extends SherlockActivity or extends SherlockFragmentActivity?

ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

I don't think you can getSupportActionBar in something that only extends SherlockFragment.

You also need to override the options menu selection:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Keep in mind, the code above would run in an activity (hence finish()). If you don't use an Activity (which would be odd to me...), then you'll need to replace that.

The simplest solution is to follow these three simple steps:

1 - Declare in the AndroidManifest which is the parent of your activity:

<activity android:theme="@style/Theme.MyApp"
            android:name="com.example.CurrentActivity" 
            android:parentActivityName="com.example.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.ParentActivity" />

2 - Add the Up icon in the action bar, simply calling from your onCreate method:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

3 - Specify the activity to open when the user presses the Up button:

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

NOTE: If you call (as suggested by @Eric):

finish();

instead of:

NavUtils.navigateUpFromSameTask(this);

your are not really performing "up navigation", since as the documentation says:

Up navigation is distinct from the back navigation provided by the system Back button. The Back button is used to navigate in reverse chronological order through the history of screens the user has recently worked with. It is generally based on the temporal relationships between screens, rather than the app's hierarchy structure (which is the basis for up navigation).

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