我遇到了一个奇怪的问题,每当我试图为我的文本视图分配位置时,第一页和第二页都会变得非常奇怪,第一页为0,第二页为0三说1,每当我刷回第0页时,它就说1。
这是我的活动(theabcactivity):
public class theabcactivity extends FragmentActivity {
String[] heabc;
int backColor;
int currentnumber = 0;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_theabcactivity);
heabc = getResources().getStringArray(R.array.heabc);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setPageTransformer(true, new ZoomOutPageTransformer());
mPagerAdapter = new
ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setCurrentItem(0);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int CurPage) {
currentnumber = CurPage;
Log.e("CurPage", " " + CurPage);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Random rnd = new Random();
backColor = Color.argb(40, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
return new theabc();
}
@Override
public int getCount() {
return heabc.length;
}
}
}
我在这里指定了currentnumber = CurPage;,我稍后会在我的片段中重复使用。
片段代码(theabc):
public class theabc extends Fragment {
TextView itemscount;
String [] heabc;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.theabc, container, false);
LinearLayout contentll = (LinearLayout)rootView.findViewById(R.id.content);
heabc = getResources().getStringArray(R.array.heabc);
itemscount = (TextView)rootView.findViewById(R.id.itemcount);
theabcactivity abcact = (theabcactivity) getActivity();
contentll.setBackgroundColor(abcact.backColor);
itemscount.setText(String.valueOf(abcact.currentnumber));
Log.e("www", "current number value" + abcact.currentnumber);
return rootView;
}
}
另外一件事我注意到,每当这个活动打开时,它会加载片段两次,因为我收到了以下日志:
E/www: current number value0
E/www: current number value0
它让我得出结论,当Viewpager打开时,它会加载前两个项目,第一个项目和第二个项目。 如何解决它将第一项加载为0,下一项加1等等?
提前致谢。