我遇到了以下问题,第一个viewpager错误地显示了第二个viewpager的内容,在滑动到第二个viewpager后,内容相同,正确地显示了第二个viewpager。为了解决这个问题,我必须滑动到第三个viewpager让FragmentStatePagerAdapter重新加载,然后第一个viewpage的内容就会正确显示。
package com.example.android.effectivenavigation;
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.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
static int myViewPagerItem;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyPageAdapter mFragmentStatePagerAdapter = new MyPageAdapter(getSupportFragmentManager());
setContentView (R.layout.refuel_viewpager);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(mFragmentStatePagerAdapter);
}
public static class MyPageAdapter extends FragmentStatePagerAdapter {
public MyPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
myViewPagerItem = i;
return new ViewFragment();
}
@Override
public int getCount() {
return 10;
}
}
public static class ViewFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.view, container, false);
TextView text1 = (TextView) v.findViewById(R.id.text1);
text1.setText("Page: " + myViewPagerItem);
return v;
}
}
}