I have an app that uses fragments to create a page adapter. I use this to create a swipe tab which loads a different fragment. Each fragment loads webview which displays a specially formatted website. Right now my app only loads the fragments it is on and the ones to the left and right of it. I would like to load all six tabs at once and never again. Is there a way to do this?
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
ViewPager viewPager=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
FragmentManager fragmentManager=getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public Fragment getItem(int i) {
Fragment fragment=null;
if(i==0)fragment=new Introduction();
if(i==1)fragment=new Arena();
if(i==2)fragment=new Game();
if(i==3)fragment=new Robot();
if(i==4)fragment=new Tournament();
if(i==5)fragment=new Glossary();
return fragment;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 6;
}
public CharSequence getPageTitle(int position) {
String title=new String();
if(position==0)return "Summary";
if(position==1)return "The Arena";
if(position==2)return "The Game";
if(position==3)return "The Robot";
if(position==4)return "The Tournament";
if(position==5)return "Glossary";
return null;
}
}
You can't use ViewPager to swipe between Activities . You need to convert each of you five Activities into Fragments , then combine everything in one FragmentActivity with the Adapter you use with ViewPager .
call setOffscreenPageLimit with a number higher than half your fragments. This will force the viewpager to create and keep all of the fragments created as you have in your adapter.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
// use a number higher than half your fragments.
viewPager.setOffscreenPageLimit(4);
FragmentManager fragmentManager=getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With