2014-01-06 43 views
7

我有一個使用片段創建頁面適配器的應用程序。我用它來創建一個加載不同片段的滑動選項卡。每個片段都會加載顯示特殊格式網站的webview。現在我的應用程序只加載它所在的碎片以及其左側和右側的碎片。我想一次加載全部六個標籤,永遠不會再加載。有沒有辦法做到這一點?在應用程序開啓時加載所有片段

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; 
    } 
} 

回答

22

打電話setOffscreenPageLimit與一個數字高於你的片段的一半。 這將強制viewpager創建並保留您在適配器中創建的所有片段。

@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));  
} 
+1

好的..這幫了我 – pratz9999

相關問題