我的ViewPager有一个小问题, 当我滚动以更改片段时,该过程将花费更多时间才能更改片段。 原因是由于对碎片进行初始化需要花费更多时间。
您有什么建议可以帮助我吗?
答案 0 :(得分:1)
这是我查看的寻呼机代码,希望对您有所帮助。如果您有共享错误日志和代码,那么我会以更好的方式为您提供帮助。
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private Button next;
private Button back;
private WalkThroughAdapter viewPagerAdapter;
private WormDotsIndicator indicators;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT < 16) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}else {
View decorView = getWindow().getDecorView();
// Hide the status bar.
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
// Remember that you should never show the action bar if the
// status bar is hidden, so hide that too if necessary.
}
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
next = (Button) findViewById(R.id.next);
back = (Button) findViewById(R.id.back);
indicators = (WormDotsIndicator) findViewById(R.id.indicator);
FadeOut transformation =new FadeOut();
viewPagerAdapter = new WalkThroughAdapter(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter);
indicators.setViewPager(viewPager);
viewPager.setPageTransformer(true,transformation);
}
@Override
protected void onStart() {
super.onStart();
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() + 1 < 3) {
viewPager.setCurrentItem(nextitem(), true); //getItem(-1) for previous
}
}
});
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() - 1 >= 0) {
viewPager.setCurrentItem(previtem(), true); //getItem(-1) for previous
}
}
});
}
private int nextitem() {
return viewPager.getCurrentItem()+1;
}
private int previtem() {
return viewPager.getCurrentItem() - 1;
}
private class WalkThroughAdapter extends FragmentPagerAdapter{
public WalkThroughAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
Walkthrough1 firstScreen = new Walkthrough1();
return firstScreen;
case 1:
Walkthrough2 secaondScreen = new Walkthrough2();
return secaondScreen;
case 2:
Walkthrough3 thirdScreen = new Walkthrough3();
return thirdScreen;
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
private class FadeOut implements ViewPager.PageTransformer{
@Override
public void transformPage(View page, float position) {
page.setTranslationX(-position*page.getWidth());
page.setAlpha(1-Math.abs(position));
}
}
}
还要检查您的片段布局,它们可能正在使用一些大图像,这可能会导致在主UI线程上加载问题
答案 1 :(得分:0)
在主线程上做太多工作可能会导致不良的用户体验。 如果您在工作线程上转移工作逻辑,则可能会解决问题。
答案 2 :(得分:0)
当有很多片段并且该片段包含ListView时,使用RecycleView代替ListView非常重要。