Navigation up button: go to previous Acitivty with prev fragment

Sunday, July 6, 2014

I need your help regarding my application flow.

MainActivity (with Navigation Drawer)
-- Fragment A
-- Fragment B
-- Fragment C (articles list view)

-- Fragment D (article detail view)

Fragment C (MainActivity) displays a list of items (ListView). Selecting an item leads to fragment D (handle by ArticleActivity) which presents that item in more detail.

Fragment D displays a "Up" button that should allow the user to returns to previous screen (the detail view). The problem is that when the "Up" button is pressed the previous activity is displayed but not the previous activated fragment (the defaut fragment (A) is instead displayed).

My current code:

public class FragmentC extends Fragment {
public static FragmentC newInstance() {
FragmentC fragment = new FragmentC();
return fragment;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_courses, container, false);

// Somewhere in my code I have a onClickListener to launch the detail view activity
setOnClickListener(new OnCardClickListener() {
public void onClick(Card card, View view) {
Intent i = new Intent(getActivity(), ArticleActivity.class);
i.putExtra("articleIndex", mArticle.getId());

return view;

public class ArticleActivity extends Activity {
private long mArticleIndex;

public void onCreate(Bundle savedInstanceState) {

mArticleIndex = getIntent().getExtras().getLong("articleIndex", 0);

// Set up action bar:
// Specify that the Home button should show an "Up" caret, indicating that touching the
// button will take the user one step up in the application's hierarchy.
final ActionBar actionBar = getActionBar();

// Place an ArticleFragment as our content pane
ArticleFragment fragment = ArticleFragment.newInstance(mArticleIndex);
getFragmentManager().beginTransaction().replace(, fragment).commit();

public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// This is called when the Home (Up) button is pressed in the action bar.
Intent upIntent = new Intent(this, MainActivity.class);
return true;
return super.onOptionsItemSelected(item);

I think that I can resolve this issue by passing parameters to my Intent. For example i.putExtra("displayFragment", FragmentD) and then on the MainActivity retrieve it and tell to the FragmentManager to display the wanted fragment. I do not know if it's can work.

But it's maybe not the right way to achieve that?

Do you have any better workaround?