Safari
Safari

Reputation: 11935

How do I show back button in Activity

I tried this code to show my ProfileActivity:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_profile) {
            Intent mainIntent = new Intent(Contracts.this, Profile.class);
            startActivity(mainIntent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

When I click on Profile menu Item I can see my ProfileActivity but I not have any back button on my ActionBar to return in my previous activity.

So, how can I show some back button? Is correct my code to display an activity from my menu?

Upvotes: 6

Views: 9958

Answers (2)

Machado
Machado

Reputation: 14489

At your Profile Activity check if there's something missing:

public class Profile extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // etc...
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.action_profile:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

The function NavUtils.navigateUpFromSameTask(this) requires you to define the parent activity in the AndroidManifest.xml file

    <activity android:name="com.example.ServicesViewActivity" >
            <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.ParentActivity" />
    </activity>

http://developer.android.com/design/patterns/navigation.html#up-vs-back

Upvotes: 9

Apurva
Apurva

Reputation: 7901

In onCreate() method of Profile.class put this,

getActionBar().setDisplayHomeAsUpEnabled(true);

and this,

@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{       
    onBackPressed();
    return true;
}

Upvotes: 5

Related Questions