我有一个实现ViewPager的片段,在这个片段中,我使用onSaveInstanceState()
方法保存ViewPager的状态。我可以使用viewPager.getCurrentItem()将其保存在捆绑软件中,但是当我恢复ViewPager的状态时,viewPager.setCurrentItem()
似乎不起作用。
如何正确保存片段状态?
这是我的片段代码
public class HomeFragment extends Fragment {
private ViewPager viewPager;
private ViewPagerAdapter adapter;
Integer[] colors=null;
List<Model> models;
private String[] mDescriptions;
private String[] mTitle;
private String mPlayerName;
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentItem", viewPager.getCurrentItem());
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
models = new ArrayList<>();
Resources res = getResources();
mDescriptions = res.getStringArray(R.array.newGameDescription);
mTitle = res.getStringArray(R.array.newGame);
models.add(new Model(R.drawable.ic_launcher_background,mTitle[0], mDescriptions[0]));
models.add(new Model(R.drawable.ic_launcher_background,mTitle[1], mDescriptions[1]));
models.add(new Model(R.drawable.ic_launcher_background,mTitle[2], mDescriptions[2]));
models.add(new Model(R.drawable.ic_launcher_background,mTitle[3], mDescriptions[3]));
adapter = new ViewPagerAdapter(getContext(), models, mPlayerName);
int orientation = getResources().getConfiguration().orientation;
adapter.setOrientation(orientation);
View view = inflater.inflate(R.layout.fragment_home, container, false);
viewPager = (ViewPager) view.findViewById(R.id.gameModeViewPager);
viewPager.setAdapter(adapter);
viewPager.setPadding(130,0,130,0);
return view;
}
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
viewPager.postDelayed(new Runnable() {
@Override
public void run() {
int item = savedInstanceState.getInt("currentItem");
viewPager.setCurrentItem(item);
}
}, 100);
}
}
}
欢迎您提出任何建议和评论,
答案 0 :(得分:0)
onCreateView 不会从onSaveInstanceState
返回束值,而您必须从onActivityCreated
来获取束值
@public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
viewPager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
int item = savedInstanceState.getInt("currentItem");
viewPager.setCurrentItem(item);
}
});
}