AndroLife
AndroLife

Reputation: 938

Communication between Fragment Inside viewpager and fragment that have the viewpager

I have an activity that host a fragment with Two views a mapview and viewpager that contain fragments. I don't know how to make the fragment inside viewpager communicate with the principal fragment (the fragment that have viewpager) This is the code I use :

public class ViewPagerAdapter extends FragmentPagerAdapter implements Serializable {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
    public List<Step> steps = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    public void addFragment(StepsFragment fragment, Step step){
        fragment.getSteps().setText(step.getHtmlInstruction());
        mFragmentList.add(fragment);
        steps.add(step);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return null;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    }
}

I get an null pointer exception because all the fields are not initialsed ... I should be doing something wrong please help.

Upvotes: 0

Views: 335

Answers (1)

user3250969
user3250969

Reputation:

The fragment, which contains view pager, can be accessed via getSupportFragmentManager by id/tag.

// Warning: getActivity() can be null in some cases.
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.your_fragment);
if (fragment instanceof FragmentB)
{
   FragmentB fragmentB = (FragmentB) fragment;

}

Another approach is to do the same, but via your activity. FragmentA->Activity->FragmentB.

https://developer.android.com/training/basics/fragments/communicating.html

Upvotes: 1

Related Questions