To use the fragment manager inside your Fragment, simply call
getActivity().getFragmentManager()
instead of getFragmentManager()
. Implementing this in your OnItemClickListener
should suffice.
Changing Fragments inside Activity through onListItemClick()
-
03-10-2022 - |
Question
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.
Solution
OTHER TIPS
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 theonDetach
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow