abekenza
abekenza

Reputation: 1090

How to return to previously opened tab on back button press

I have a TabLayout with 3 sections. Each section contains list of items.

When I click item on second section, I start new activity like this.

Intent intent = new Intent(getContext(), SecondDetailActivity.class);
startActivity(intent);

Inside of SecondDetailActivity I have an action bar with back button. And I handle click of back button like this.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home: {
            onBackPressed();
        }
    }
    return super.onOptionsItemSelected(item);
}

My problem is:

When I click device's back button, the selected tab of the tablayout is Second tab. But when I click on action bar navigation button, the selected tab is First tab.

How can I make action bar's behavior same as device's back button?

enter image description here

Upvotes: 0

Views: 553

Answers (1)

Paresh
Paresh

Reputation: 6857

Try to return true while your case is android.R.id.home
like

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home: {
            onBackPressed();
            return true;
        }
    }
    return super.onOptionsItemSelected(item);
}

Upvotes: 3

Related Questions