处理ViewPager的方向更改

时间:2018-11-22 05:19:00

标签: android android-viewpager bundle orientation

我已经搜索了整个Internet,但无法解决我的问题。 有一个带有适配器的片段:

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
CURRENT_TAB = viewPager.getCurrentItem();
outState.putInt("current_tab", CURRENT_TAB);
}

好的,很好,我当前的页面= 2已保存。 然后我有:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppPreferences appPreferences = new AppPreferences(getContext());

if (savedInstanceState != null) {
    CURRENT_TAB = savedInstanceState.getInt("current_tab");
    viewPager.post(new Runnable() {
        @Override
        public void run() {
            viewPager.setCurrentItem(CURRENT_TAB);
        }
    });
}

......

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  Bundle savedInstanceState) {
 super.onSaveInstanceState(savedInstanceState);
 view = inflater.inflate(R.layout.fragment_orderlist, container, false);
 savedInstanceState.getString("current_tab"));

在两种情况下,我的savedInstanceState为null。怎么了?

1 个答案:

答案 0 :(得分:1)

   // First extend your class with Fragment like

    public class Abc extends Fragment {

    private View rootView;
    private static CustomViewPager mPager;
    private static int currentPage = 0;

    // Then Required an empty public constructor

    public Abc() {

        }

        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

     rootView = inflater.inflate(R.layout.fragment_amazing_hero, container, false);
            //Now initialize the viewpager and do the magic

     mPager = rootView.findViewById(R.id.pager);
    mPager.setAdapter(new Your_Adapter(getActivity(), ArrayList));



            mPager.setPagingEnabled(false);
            int NUM_PAGES = ArrayList.size();

            return rootView;