Reputation: 3407
I have five Fragments
attached to a ViewPager
. I want to validate forms in each before sending the data to my server. So, I decided to loop through the Fragments
to see if I can reach the methods. But, I know it can't be reached like that. Below is what I tried
Fragment[] listOfFrags = {new Frag1(), new Frag2(), new Frag3(), new Frag4(),
new ExpenseFragment()};
for (int i = 0; i < listOfFrags.length; i++) {
Fragment cuurentFrag = listOfFrags[i];
boolean checker = cuurentFrag.ValidateData();<-- The unreachable destination
}
And this is my Adapter
public PagersAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = new Frag1();
switch (position) {
case 0:
fragment = new Frag1();
break;
case 1:
fragment = new Frag2();
break;
case 2:
fragment = new Frag3();
break;
case 3:
fragment = new Frag4();
break;
case 4:
fragment = new Frag5();
}
return fragment;
}
@Override
public int getCount() {
return 5;
}
Upvotes: 0
Views: 474
Reputation: 4332
What you could do is use your adapter to store a list of its Fragments as per the sample below.
private class SectionsPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Fragment0;
break;
case 1:
fragment = new Fragment1;
break;
case 2:
fragment = new Fragment2;
break;
}
return fragment;
}
@Override
public int getCount() {
return 3;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
public SparseArray<Fragment> getRegisteredFragments(){
return registeredFragments;
}
}
As ProtossShuttle said you could create a superclass (or interface depending on your needs) with a validate method which you can call on each Fragment by iterating through this list.
Upvotes: 0
Reputation: 1673
I guess what you mean is to call the ValidateData()
method of each fragment. You can write a super class extending Fragment
which contains the ValidateData()
method and make all your other fragments extend the super class. When you want to call the ValidateData()
method, just cast your fragments to the super class. And I guess there're also some other problems in your code.
Upvotes: 1