-1

Description:

I have an activity (Father activity) which has a fragment (Father fragment) inside. This fragment is tabbed and has two fragments (Fragment A and Fragment B) that are changed with view pager.

Father activity sends data to Father fragment which has to take them to Fragment B

Question:

What can I do with Father fragment to take data to Fragment B (which is inside a view pager)?

Extra:

Someone told me I can use interface and I've tried to study it but I couldn't find any good tutorial / explanation.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Tomas M
  • 287
  • 4
  • 16
  • Hi @Tomas you can store viewpager fragment instance inside father fragment and using that fragment instance you call a method in child fragment which can update Data. – Deepak Mar 02 '20 at 17:53
  • Hello and thanks for answering. Could you explain it more detailed? – Tomas M Mar 02 '20 at 18:21
  • @Deepak that would actually result in crashes in production unless you use https://stackoverflow.com/questions/54279509/how-to-get-elements-of-fragments-created-by-viewpager-in-mainactivity/54280113#54280113 to get the fragment instances – EpicPandaForce Mar 02 '20 at 19:32

1 Answers1

0

Hi @Tomas I have Done like this

 private class ViewPagerAdapter extends FragmentPagerAdapter {

    private Fragment fragment1 = Fragment1.getInstance();
    private Fragment fragment2 = Fragmen2.getInstance();

    ViewPagerAdapter(FragmentManager supportFragmentManager) {
        super(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);

    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return fragment1;
        } else {
            return fragment2;
        }
    }


    @Override
    public int getCount() {
        return  2 ;
    }

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

    Fragment1 getFragment1() {
        return (Fragment1) fragment1;
    }

    Fragment2 getFragment2() {
        return (Fragment2) fragment2;
    }
}

this is my Fragemnt2 code:

public class Fragment2 extends Fragment {

private TextView text;
public static Fragment2 getInstance() {
    return new Fragment2();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragmant_2, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
     text = view.findViewById(R.id.text2);

}

public void reloadView(String data){
   text.setText(data);
}



}

and from viewpager adapter I call method of faragment 2 like this

adapter.getFragment1().reloadView("data");
Deepak
  • 127
  • 4
  • 11