从纵向更改为横向时 ViewPager 上的页面位置

Page position on a ViewPager when change from portrait to landscape

我在为图库编程时从纵向更改为横向时遇到问题。 PageAdapter.instantiateItem(View container, int position) 方法中的页面位置在更改屏幕方向时变为 0。我想存储当前页面位置,以便在方向改变时保留在该页面中。

您需要将当前显示的页面存储在您保存的实例状态中。如何保存状态,请阅读documentation.

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the current item
    savedInstanceState.putInt("current_item", pager.getCurrentItem());

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

方向改变后,该状态可以是 restored 并用于设置寻呼机的位置。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentItem = savedInstanceState.getInt("current_item");
    }
}

呼叫 pager.setCurrentItem(mCurrentItem); 例如在您的 onStart()onResume() 方法中。

有关如何获取和设置当前选定项的信息,请阅读 ViewPager 文档:

getCurrentItem()

setCurrentItem()