so i'm using ViewPager to make my app much faster , instead of using an activity for each layout.
the problem is , in activity you can write your code inside onCreate and it will only starts when you start the activity , right?
but when you go with fragments and fragmentPagerAdapter and use ViewPager for them.
all your fragments going to start their (onCreateView) together even if your ViewPager only showing the First Fragment!
if you are you playing a sound or animation on the start of a fragment , it will starts in the background !
here's my fragmentPagerAdapter class:
public class PagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitle = new ArrayList<>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitle.add(title);
}
}
and i have this (second Fragment) that i don't want it to starts without being seleceted!
public class GameFragment extends Fragment{
private View gameLayout
private Animation showBtn;
private Button button;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
gameLayout = inflater.inflate(R.layout.game_layout, container, false);
button = gameLayout .findViewById(R.id.button);
// loading my anim xml file
showBtn = AnimationUtils.loadAnimation(getContext(),R.anim.btn_show);
button.startAnimation(showBtn);
loadLevel();
return gameLayout
}
finally this is my Activity that have ViewPager :
public class ControllerActivity extends AppCompatActivity {
public CustomPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controller);
viewPager = findViewById(R.id.viewPager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment(),"Home");
adapter.addFragment(new GameFragment(),"Game");
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
}
i need your help to show me my mistakes here and what is the correct way