Jethro Monzada Jethro Monzada - 2 months ago 16
Android Question

Empty fragment after reuse

I have one activity with 2 buttons that serve as a menu and one fragment which has a viewpager. The fragment is being added at the activity after a button click and the views inside this fragment changes depending on the button that was clicked. Here is an example implementation:

Fragment fragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
//..
}

@Override
public void onClick(View v) {
if(v==button1){
fragment = new Fragment1().newInstance(ArrayStringValues1, ArrayStringValues2);
fragmentChanger();
}else if(v==button2){
fragment = new Fragment1().newInstance(ArrayStringValues3, ArrayStringValues4);
fragmentChanger();
}
}

public void fragmentChanger(){
FragmentManager fm2 = getSupportFragmentManager();
fragmentTransaction = fm2.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fragment);
fragmentTransaction.commit();
}


If I click button 1 or 2 for the first time, the fragment and its content are being displayed successfully but when I click button 1 or 2 for the second time, the fragment's viewpager contents displays nothing.

Answer

These lines don't make sense (like whitaay mentioned)

fragment = new Fragment1().newInstance(ArrayStringValues1, ArrayStringValues2);

fragment = new Fragment1().newInstance(ArrayStringValues3, ArrayStringValues4);

They should read:

fragment = Fragment1.newInstance(ArrayStringValues1, ArrayStringValues2);

fragment = Fragment1.newInstance(ArrayStringValues3, ArrayStringValues4);

You should also show the code for the "fragments inside of a fragment" which will probably need getChildFragmentManager()