I have one big form broken into 3 fragments. Fragments are contained into FragmentPagerAdapter, so they can be swiped as pages. As there are a lot of calls, I think it wouldn’t be practical to call a interface from the fragment to the activity on each control that is changed. Is there a way to call a method or get a property of the fragment on each page swipe?
Here's the current code:
final List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setOffscreenPageLimit(3); //This is necessary to prevent the destruction of the last fragment, otherwise the dynamically added views get lost
pager.setAdapter(pageAdapter);
As the offscreenlimit is increased to deal with the issue that programmatic added views as childs to a layout in one of the fragments get destroyed when the fragment is not visible, the onPause() is not applicable, otherwise it would've been rather simple to just call the interface in it.
I've though about overriding the OnPageChangeListener of the pager, however I couldn't find how to get the data I need. Here's part the code in the fragments:
The interface from the fragment to the activity is implemented to according to this answer https://stackoverflow.com/a/9977370/1927033
Interface
public interface DataPassIF {
public void passPartForm(UForm pageFromForm);
}
DataPassIF dataPasser;
@Override
public void onAttach(Activity a){
super.onAttach(a);
dataPasser = (DataPassIF) a;
}
This is the fragment that if the limit is not increased, the seekbar's get destroyed.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View fragment = inflater.inflate(R.layout.page3, container, false);
LinearLayout ll = (LinearLayout) fragment.findViewById(R.id.p3_ll);
RelativeLayout rl = (RelativeLayout) fragment.findViewById(R.id.p3_rl);
int child = rl.getChildCount();
for (int i = 0; i < child; i++) {
View v = rl.getChildAt(i);
if (v instanceof CheckBox) {
v.setOnClickListener(onCickAdder(fragment.getContext()));
}
}
return fragment;
}
private View.OnClickListener onCickAdder(final Context context) {
return new View.OnClickListener() {
@Override
public void onClick(View view) {
if (((CheckBox) view).isChecked()) {
SeekBar nsb = createSeekBar(context);
//TODO clear up this with proper id generation
nsb.setId(imak++);
view.setTag(nsb.getId());
ll.addView(nsb);
} else {
ll.removeView(ll.findViewById((Integer) view.getTag()));
}
}
};
}
private SeekBar createSeekBar(Context context) {
SeekBar sb = new SeekBar(context);
sb.setMax(20);
sb.setProgress(10);
return sb;
}