Kasper Sølvstrøm Kasper Sølvstrøm - 3 months ago 8
Android Question

Android UP button goes to mainActivity instead of current

I have 3 activities:


  • MainActivity (start activity with grid view)

  • FragmentActivity (full screen image slider accessed from grid view)

  • InfoActivity (blank activity opened from menu in either Main or Fragment)



When I go from MainActivity to InfoActivity:

startActivity(new Intent(MainActivity.this, InfoActivity.class));


and press the "up" button I get back to main activity.

When I go from FragmentActivity to InfoActivity

startActivity(new Intent(this, InfoActivity.class));


and press the "up" I STILL get back to MainActivity.

I know it's because my MainActivity is the parent of Info.

But how do I make the "up" behave like the "back" button, so that I can go from InfoActivity to FragmentActivity?

Any help will be much appreciated!

Answer

You have to override onOptionsItemSelected in the InfoActivity class to intercept the "up" button and call onBackPressed from there. Like so:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item != null && item.getItemId() == android.R.id.home) {
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
Comments