Reputation: 3450
I have a slide panel that has one fragment inside, that has one more fragment per section (you will see in the screenshot).
I have the first section (Fragment 0) that stores the items selected in another adapters. How can I reference those fragments and adapters, to be able to modify items on the adapters.
I've store the fragment with:
private void setUpOperateOptionSectionItemFragment(OperateModel model, int fragmentPosition){
LinearLayout container = getSectionContainer();
activityView.getLaySectionsContainer().addView(container);
OperateOptionSectionItemFragment fragment = OperateOptionSectionItemFragment.newInstance(model, fragmentPosition, this);
FragmentManager fragmentManager = activityView.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(container.getId(), fragment, OPERATE_OPTION_FRAGMENT_TAG+fragmentPosition);
fragmentTransaction.commit();
operateOptionSectionItemFragmentList.add(fragment);
}
When I click on an item of adapters of fragments 1, 2, 3... I need to add or delete (if exists) the item in the adapter of the fragment 0.
How can I access to this adapter, how to differenciate if I use the same Adapter for all.
Upvotes: 1
Views: 867
Reputation: 1888
You can access other fragments through activity callbacks. It will look like this:
Create interface
public interface MyActivityCallback {
void doSomeWithFragment();
}
Let your activity override this interface
public MyActivity extends AppCompatActivity implements MyActivityCallback {
...
MyFragment fragment1;
MyFragment fragment2;
...
void doSomeWithFragment() {
...
fragment1.doSome();
}
}
Find this interface inside your fragment. It's better to do this inside onAttach()
method:
public MyFragment extends Fragment {
MyActivityCallback callback;
@Override
public void onAttach(Context context) {
super.onAttach(context);
callback = (MyActivityCallback) context; // context - is your activity, that added this fragment
}
...
public void someFunction() {
// here you want to change some in your other fragments:
callback.doSomeWithFragment();
}
}
So, in few words:
Activity stores references to all child fragments
Fragments store references to interface callback, that is implemented by parent activity.
So, you call activity to do some through this callback, and activity is doing that work, cause it has all fragments' references.
Upvotes: 3