在app开放时加载所有片段

时间:2014-01-06 20:32:25

标签: android android-fragments android-webview

我有一个使用片段创建页面适配器的应用程序。我用它来创建一个滑动选项卡,加载一个不同的片段。每个片段加载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;
    }
}

2 个答案:

答案 0 :(得分:30)

使用高于片段一半的数字来呼叫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 :(得分:0)

在科特林:

viewPager.offscreenPageLimit = size / 2

默认情况下offscreenPageLimit = 1,这意味着它将在当前片段的两侧加载1个片段。总共3片