2

我有嵌套在一個片段ViewPager,當設備改變方向,我想保存和恢復ViewPager是在哪一頁。目前,我正在這樣做:setCurrentItem嵌套viewpager

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    mViewPager = (ViewPager) inflater.inflate(R.layout.activity_albumpicker, container, false); 

    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the activity. 
    mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager()); 

    setRetainInstance(true); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    if(savedInstanceState != null) { 
     mViewPager.setCurrentItem(savedInstanceState.getInt("pagerState"), false); 
    } 
    return mViewPager; 
} 

@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putInt("pagerState", mViewPager.getCurrentItem()); 
} 

期間onSaveInstanceState值被保存是正確的,在onCreateView旋轉savedInstanceState.getInt("pagerState")值後也是正確的。但沒有任何反應,ViewPager停留在它的默認頁面上,logcat中沒有任何內容。我很難過。

+0

問題在於你的viewpager擁有子視圖(Fragment?我猜),然後直到這些子視圖被完全創建,你的viewpager的項數應該是0.你可以檢查你的子視圖的日誌來製作suare。 –

+0

實際產品數量爲1。如果所有的孩子都被裝上了,那應該是3。儘管它確實有助於縮小它的範圍,但仍然沒有真正告訴我如何解決這個問題,謝謝 – Nick

+0

由於旋轉屏幕觸發了一些方法(例如onConfigurationChanged),並且它也取決於您的主機Activity的Manifest設置,你能告訴我你是如何擁有他們的嗎?部分信息沒問題。 –

回答

2

經過幾個小時的審查一些特定的東西,我想出了以下解決方案(這是一種通常的做法,我想)。我包括您已完成的兩個步驟以及其他必要步驟。

    1. 呼叫setRetainInstance(true);(你這樣做)
  • 設置片段的節能狀態。 (你已經這樣做了)
  • 在主機活動,請撥打以下,以確保您的片段已經保存在活動的狀態:

Here is a snippet:

... (other stuffs) 

Fragment mainFragment; // define a local member 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // After you rotate your screen, by default your Activity will be recreated  
    // with a bundle of saved states, i.e at this point, savedInstanceState is  
    // not null in general. If you debug it, you could see how it saved your 
    // latest FragmentTransactionState, which hold your Fragment's instance 

    // For safety, we check it here, and retrieve the fragment instance. 
    mainFragment = getSupportFragmentManager().findFragmentById(android.R.id.content); 
    if (mainFragment == null) { 

    // in very first creation, your fragment is null obviously, so we need to 
    // create it and add it to the transaction. But after the rotation, its 
    // instance is nicely saved by host Activity, so you don't need to do 
    // anything. 

    mainFragment = new MainFragment(); 
    getSupportFragmentManager().beginTransaction() 
     .replace(android.R.id.content, mainFragment) 
     .commit(); 
    } 
} 

這就是我做的,使它的工作原理。希望這可以幫助。

+0

啊,這個工程。感謝您的幫助! – Nick

相關問題