0
votes

I have an Activity "A" which contains a view pager that contains 5 fragments. One of the fragment has over 7-8 fragments added programmatically. Each fragment is instantiated using the static method instance() defined in the respective fragment.

for(int i = 0 ; i < 10; i++) {
    CustomFragment fragment = (CustomFragment) Class.forName(classNameList.get(i)).instance();
    getFragmentManager().beginTransaction().add(R.id.parentLinearLayout, fragment, fragmentTag).commitAllowingStateLoss();
}

Everything works fine when this activity is launched and traversed across different fragments.

But if I launch an activity "B" and return to activity "A". All the other fragments in the view pager load fine except the fragment that contains the set of fragments. It shows up as a blank screen. What could be the problem?

1
Do you initialize that fragment using a constructor?MohanadMohie
yes I do.. @MohanadMohie does it matter or affect in any way?i_raqz
Of course. Fragments, like Activities, are instantiated by the Android system without using the constructor, therefore the items you pass in the constructor are disregarded when Android re-instantiates the Fragment. You can add Arguments to the fragment before using in the ViewPager. I will post an answer with an example shorty.MohanadMohie
hey @MohanadMohie...i misquoted earlier. Please see the updated question. I am calling the .instance() to create the instancei_raqz
I'm sorry I can't be of any more help unless I can reproduce the problem. Consider updating your question with an MCVE.MohanadMohie

1 Answers

0
votes

You are using a constructor to instantiate your Fragment and pass your parameters, and when Android re-instantiates the Fragment it doesn't use your constructor, and hence your parameters are disregarded. You should use Arguments to pass your parameters. This is an example of how you can do so:

Inside MyFragment.java:

private static final String KEY_ITEM = "item";

public static MyFragment getFragment(String myItem) {
    MyFragment fragment= new MyFragment ();
    Bundle args = new Bundle();
    args.putString(KEY_ITEM, myItem);
    fragment.setArguments(args);
    return fragment;
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String myItem = getArguments().getString(KEY_ITEM);
}

Inside your ViewPager adapter:

    @Override
    public Fragment getItem(int position) {
        return MyFragment.getFragment("Your parameter here.");
    }

Of course, I used a single String as a parameter, you can add as much parameters as you'd like.