2

I'm pretty new to Android so I may be doing things completely wrong but I'm trying to get a fragment to open up when a list item is clicked and then to close it when it is dismissed with the back button.

I now have something working but when the back button is clicked it redraws the whole initial view. SO the listview scrolls back up to the top and reloads all the items from the db.

On the list item click in the main activity I am doing this

public void onItemSelected(String id) {
    Intent detailIntent = new Intent(this, DetailActivity.class);
    detailIntent.putExtra(Fragment.CLICKED_ID, id);
    startActivity(detailIntent);
}

Then in the activity I am using this to show it.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_open_day);

    // Show the Up button in the action bar.
    getActionBar().setDisplayHomeAsUpEnabled(true);


    if (savedInstanceState == null) {
        // Create the detail fragment and add it to the activity
        // using a fragment transaction.

        OpenDayFragment fragment = new OpenDayFragment();
        getFragmentManager().beginTransaction()
                .add(R.id.open_day_detail_container, fragment)
                .commit();
    }
}

and this to close it.

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
}

AS i said it all works but the listview and all the tabs from MainActivity seem to be completley disposed of when the activity is run. Is there a way just to show a fragment over the top and dismiss it, leaving the previosu activity intact?

Thanks

Elliot Stokes
  • 46
  • 1
  • 6

2 Answers2

2

On close button you are recreating the home activity which will as a result launch every thing again. To void that you should finish the DetailActivity that will take you back to the Home Activity.

vipul mittal
  • 17,343
  • 3
  • 41
  • 44
  • Brilliant! Easy when you know how. So I changed it to this.finish() instead of Navutils.navigateUp and all seems fine. Does that sound ok? – Elliot Stokes Aug 21 '14 at 08:46
1

It reloads it again because you are creating the MainActivity again. To avoid that try finish(); in if (id == android.R.id.home) of your DetailActivity so it closes it, keeping the preview state of the MainActivity.

Javier Mendonça
  • 1,970
  • 1
  • 17
  • 25