Android - Passing value from ListFragment to another ListFragment

后端 未结 4 526
借酒劲吻你
借酒劲吻你 2021-01-24 07:14

I have a listview containing Category of items. When I press a category title on the list, it will display another listview containing items inside the chosen Category.

4条回答
  •  佛祖请我去吃肉
    2021-01-24 07:47

    Let your FragmentActivity implement an interface that has a categorySelected(int categoryId) method.

    Inside CategoryOverviewFragment you call this when a category is selected:

    @Override
    public void onItemClick(AdapterView adapterView, View view, int i, long l) {
        ((CategorySelectedListener)getActivity()).categorySelected(i);
    }
    

    Then in the activity you implement categorySelected and replace the overview fragment with CategoryFragment.

    When you create you CategoryFragment set the cateogry ID as argument. It's best to use the newInstance pattern to setArguments().

    To replace the category overview list fragment with the category details fragment use the FragmentManager to beginTransaction() and then replace().

    Assuming the category overview fragment is added dynamically and not in XML use code like this:

    CategoryFragment newFragment = CategoryFragment.newInstance(categoryIdSelected);
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);
    
    transaction.commit();
    

    If the category list fragment is added in XML you need to remove that change it to a FrameLayout and add the fragment dynamically in the code.

提交回复
热议问题