Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Navigation Up from Activity to Fragment

I'm developing some application and I have one problem.

I have : 1. Activity A (Navigation Drawer pattern) with ListFragment in FrameLayout: xml:

    <FrameLayout
        ...>

    </FrameLayout>

    <LinearLayout
        ...>

    </LinearLayout>

</android.support.v4.widget.DrawerLayout>
  1. Activity B which shows the detail data of ListView in ListFragment.

How can I go back (using Navigation Up Button) from activity B to Activity A with saving UI of the ListFragment (Activity re-creates if I go back using Home Back). Btw, if I press the back button on my phone, activity does not re-create and returns in previous state.

like image 960
pharrell Avatar asked Dec 20 '22 04:12

pharrell


1 Answers

When you use UP navigation, then the previous activity is recreated. To prevent that from happening while you preserve the UP navigation, you can get the intent of the parent activity, and bring it to front if it exists, otherwise create it if not.

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent parentIntent = NavUtils.getParentActivityIntent(this);
            parentIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(parentIntent);
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

I also specified launchMode="singleTop" in the Manifest. but I am not sure if that was necessary.

like image 159
EpicPandaForce Avatar answered Dec 27 '22 09:12

EpicPandaForce