-4

I have a fragment on my main activity which gets loaded on click of item from nav drawer and on click of a list item from the fragment(main screen) I navigate to another activity. If I press the device back button I get my fragment screen(as expected) but if I use a tool bar and enable the the home button by saying

getSupportActionBar().setHomeButtonEnabled(true);

I get my main activity content which was prior to selecting an item from drawer. I have set parent of next activity as the main activity but I need the fragment loaded when i go back.

Rahul Ahuja
  • 812
  • 10
  • 24
  • possible duplicate of [Programmatically go back to the previous fragment in the backstack](http://stackoverflow.com/questions/10863572/programmatically-go-back-to-the-previous-fragment-in-the-backstack) – miva2 Apr 28 '15 at 08:41
  • @miva2 not exactly what i was looking for but yes can be useful in future. I got solution for my problem. will post in the answer. Thanks – Rahul Ahuja Apr 28 '15 at 09:31

2 Answers2

1

For my problem I found a solution. on click of the home button in the toolbar I killed my activity using finish() method and it worked just as i wanted. Hope it helps the needy.

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if(id == android.R.id.home)
    {
        finish();       //kill subActivity so as to get same screen which was before going to subActivity
    }

    return super.onOptionsItemSelected(item);
}
Rahul Ahuja
  • 812
  • 10
  • 24
0

Try this

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.home) {
        NavUtils.navigateUpFromSameTask(this);
    }
    return super.onOptionsItemSelected(item);
}

You need to add this getSupportActionBar().setDisplayHomeAsUpEnabled(true); along with getSupportActionBar().setHomeButtonEnabled(true);

silverFoxA
  • 4,549
  • 7
  • 33
  • 73
  • I had tried this but my mainActivity had view X then view Y and then from view Y i started another activity on click of a list item. so when i used `NavUtils.navigateUpFromSameTask(this);` i was able to go back but view X was loaded and instead i wanted view Y. Check my answer, I got the fix. – Rahul Ahuja Apr 28 '15 at 11:04