我是android的新手,所以我尝试建立Tab活动。这是我的MainActivity:

public class MainActivity extends AppCompatActivity {

Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;


protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        viewPager = (ViewPager) findViewById(R.id.viewPager);


        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragments(new A(), "A");
        viewPagerAdapter.addFragments(new B(), "B");
        viewPagerAdapter.addFragments(new C(), "C");

        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
  }
}


在活动开始时,片段A和B已经生成,但是C在等待单击C的选项卡。而且,当我从C更改选项卡时,A和B重新加载。如何在活动开始时加载所有片段?

最佳答案

使用setOffscreenPageLimit

您的情况:viewPager.setOffscreenPageLimit(2);

08-06 12:19