Enable home button ActionbarSherlock, Sherlockfragment

user1534326 picture user1534326 · Jul 23, 2012 · Viewed 13.5k times · Source

I want to enable the home button in my fragment. This question is asked earlier but for an activity.
I tried ...

 getSupportActionBar().setDisplayHomeAsUpEnabled(true);

... but this doesn't work.
Here is my code:

import com.actionbarsherlock.R;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.MenuItem;

import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

public class SafanTab extends SherlockFragment {

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.safantab, container, false);
    }

    public OnClickListener onOverClick = new OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Over_Safan.class);
            startActivityForResult(myIntent, 0);
        }
    };

    public OnClickListener onProductenClick = new OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Over_Safan.class);
            startActivityForResult(myIntent, 0);
        }
    };

    public OnClickListener onTwitterClick = new OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Over_Safan.class);
            startActivityForResult(myIntent, 0);
        }
    };

}

How can you enable a home button on SherlockFragment?

Answer

Eric picture Eric · Jul 23, 2012

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.