1

I have this Activity which at first shows a Fragment with a list of elements. This works perfectly with this code:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_act);

    if(null == savedInstanceState)
    {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        ListFragment glfragment = new ListFragment();
        fragmentTransaction.add(R.id.listfrag1, glfragment);
        fragmentTransaction.commit();
    }

}

Well I have a ListFragment and a DetailFragment. But I don't know how to do the transition when I click an element of the list. I know the fragmentTransaction.replace(), but I don't know WHEN to call it.

I thought I should use the OnListItemClick() inside the ListFragment, but I don't know how to use the FragmentManager inside the Fragment and not in the main Activity... Also I want to "export" some data to the DetailFragment as if it was a Intent, but it's not.

fcasanova
  • 197
  • 1
  • 4
  • 15

2 Answers2

2

To use the fragment manager inside your Fragment, simply call getActivity().getFragmentManager() instead of getFragmentManager(). Implementing this in your OnItemClickListener should suffice.

Boni2k
  • 3,255
  • 3
  • 23
  • 27
  • I tried this @Override public void onListItemClick(ListView l, View v, int position, long id) { FragmentManager fm = getActivity().getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); DetailFragment df = new DetailFragment(); ft.replace(R.id.listfrag1, df); ft.commit(); } but it didn't work... – fcasanova Jan 28 '14 at 11:29
  • OK my problem was that my DetailFragment was a ListFragment... facepalm for me. It worked! – fcasanova Jan 28 '14 at 11:34
1

What I would do is:

  • Define an interface with one method listItemSelected() with as an argument the id of the selected item
  • Let your activity implement this interface
  • In the onAttach of your list fragment, take the activity and keep it as a member variable, cast to the interface type. Make sure that in the onDetach you dereference it.
  • In your onListItemClick, call this method on your activity
  • In the activity, you can now do a new fragmenttransaction, this time you need to replace instead of add the fragment
  • To create your detail fragment with the correct argument (the id), use the method described here.

This should normally work fine.

Community
  • 1
  • 1
Toon Borgers
  • 3,638
  • 1
  • 14
  • 22