onCreate()在使用ViewPager

时间:2017-06-24 14:23:40

标签: android android-fragments android-viewpager android-lifecycle android-configchanges

一般情况:
我有一个带MainFragment的MainActivity。 MainFragment有一个ViewPager,我使用FragmentStatePagerAdapter根据SqliteDatabase的内容显示DetailFragments。此数据库的内容在LocationActivity中可见并可管理。当我点击LocationActivity中的项目时,我使用intent.putextra附加项目的位置,然后在MainFragment的ViewPager中显示正确的位置。当我在LocationActivity中添加项目时,它会在SharedPreferences中保存项目的位置,并在MainFragment中获得正确的位置,以显示我刚刚添加的项目的片段。

问题:
它可以工作,但是当配置发生变化时,我会丢失ViewPager选择的实际页面。所以我用onSaveInstanceState()保存位置,如果它不为null我在onCreateView()和onViewCreated()中检索它我会通过if语句来获取ViewPager.setCurrentItem()所需的位置,具体取决于条件。但是然后第二次调用onCreate(),然后onSaveInstanceState()为null,我丢失了在配置更改之前选择的页面。你知道它为什么被叫两次吗?我该怎么做才能防止这种情况发生?谢谢你的帮助

日志

06-24 09:15:05.974 activityMain.MainFragment: onLoadFinished() onPageSelected() 2
06-24 09:15:08.276 activityMain.MainFragment: onSaveInstanceState() 2
06-24 09:15:08.320 activityMain.MainFragment: onCreate()
06-24 09:15:08.342 activityMain.MainFragment: onCreateView()
06-24 09:15:08.342 activityMain.MainFragment: onCreateView() savedInstanceState Position: 2
06-24 09:15:08.349 activityMain.MainFragment: onViewCreated() get position from mCurrentPositionState 2
06-24 09:15:08.349 activityMain.MainFragment: onActivityCreated()
06-24 09:15:08.394 activityMain.MainFragment: onCreate()
06-24 09:15:08.396 activityMain.MainFragment: onCreateView()
06-24 09:15:08.401 activityMain.MainFragment: onViewCreated()) get position from SharedPreferences 4
06-24 09:15:08.401 activityMain.MainFragment: onActivityCreated()
06-24 09:15:08.407 activityMain.MainFragment: onResume()
06-24 09:15:08.458 activityMain.MainFragment: restartCursorLoader
06-24 09:15:08.508 activityMain.MainFragment: onLoadFinished()
06-24 09:15:08.537 activityMain.MainFragment: onLoadFinished() setCurrentItem: 4

最小,完整且可验证的示例

MainFragment.java

public class MainFragment extends Fragment {

    public MainFragment() {
        // Required empty public constructor
    }

    private static final String TAG = MainFragment.class.getName();
    private static final String PAGE_SELECTED = "state_instance";

    private MainPagerAdapter mAdapter;
    private ViewPager mViewPager;

    private int mLocationPosition;

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

        if (savedInstanceState != null) {
            mLocationPosition = savedInstanceState.getInt(PAGE_SELECTED);
            Log.i(TAG, "onCreateView() savedInstanceState not null, position: " + mLocationPosition);
        } else {
            mLocationPosition = 0;
            Log.i(TAG, "onCreateView() savedInstanceState null, position: " + mLocationPosition);
        }

        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
        mAdapter = new MainPagerAdapter(getActivity().getSupportFragmentManager());
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(mLocationPosition, false);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mLocationPosition = position;
                Log.i(TAG, "onActivityCreated() mLocationPosition value: " + mLocationPosition);
        }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(PAGE_SELECTED, mLocationPosition);
        Log.i(TAG, "onSaveInstanceState() mLocationPosition value: " + mLocationPosition);
        super.onSaveInstanceState(outState);
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, new MainFragment());
        fragmentTransaction.commit();
    }
}

MainDetailFragment

public class MainDetailFragment extends Fragment {

    private static final String TAG = MainDetailFragment.class.getName();
    private TextView mTextViewLocation;

    protected static final String ARGUMENT_PAGE = "location_page";
    protected static final String ARGUMENT_NAME = "location_name";

    private String mLocation;

    public MainDetailFragment() {
    }

    protected static MainDetailFragment newInstance(int page, String locationName) {
        MainDetailFragment mainDetailFragment = new MainDetailFragment();
        Bundle arguments = new Bundle();
        arguments.putInt(MainDetailFragment.ARGUMENT_PAGE, page);
        arguments.putString(MainDetailFragment.ARGUMENT_NAME, locationName);
        mainDetailFragment.setArguments(arguments);
        return mainDetailFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments().containsKey(ARGUMENT_NAME)) {
            mLocation = getArguments().getString(ARGUMENT_NAME);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main_detail, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTextViewLocation = (TextView) view.findViewById(R.id.tv_city_name);
        mTextViewLocation.setText(mLocation);
    }
}

MainPagerAdapter

public class MainPagerAdapter extends FragmentStatePagerAdapter {

    private static final String TAG = MainPagerAdapter.class.getName();

    private static int NUM_ITEMS = 3;

    public MainPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    // Returns total number of pages
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0: 
                return MainDetailFragment.newInstance(0, "Paris");
            case 1: 
                return MainDetailFragment.newInstance(1, "London");
            case 2: 
                return MainDetailFragment.newInstance(2, "New York");
            default:
                return null;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您需要确保在配置更改后第二次不添加MainFragment。您应该将活动更新为:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    if (savedInstanceState != null) {
        return;
    }

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, new MainFragment());
    fragmentTransaction.commit();
}

原因是Activity本身已经添加了MainFragment的记录,并会在配置更改后自动恢复它。如果您再次执行相同的事务 ,首先您将看到已恢复的MainFragment启动,然后它将被新的Fragment事务中的新事件替换为一个新的,不同的MainFragment将经历自己的初始化过程。这会导致对onCreate的{​​{1}}多次调用。

答案 1 :(得分:-1)

在MainFragment的onCreate()中调用它

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, "onCreate()");
    setRetainInstance(true);
}