Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Orientation change with ViewPager + FragmentPagerAdapter

I'm having trouble handling screen orientation change with ViewPager and FragmentPagerAdapter. It works fine on application startup but the fragments inside the viewpager are not visible after orientation change (maybe lost). How do I fix this issue. Following is the structure of my activity: enter image description here

edit: This is the manifest file

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />

<application
    android:name="com.test.myapp.NetworkManager.TBVolleyInstance"
    android:allowBackup="true"
    android:icon="@drawable/launcher"
    android:label="@string/app_name"
    android:theme="@style/CustomActionBarTheme">
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".Home"
        android:label="@string/app_name"
        android:windowSoftInputMode="adjustNothing" >
    </activity>
    <activity
        android:name=".RouterActivity"
        android:label="@string/app_name" >
        <intent-filter android:label="@string/app_name" >
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

FragmentPagerAdapter implementation:

public class PagerAdapter extends FragmentPagerAdapter{

public PagerAdapter(FragmentManager fm) {
    super(fm);

}

@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        return new Fragment1();
    case 1:
        return new Fragment2();
    }
    return null;
}

@Override
public int getCount() {
    return 2;
}

@Override
public float getPageWidth(int position){ 
    return(1.0f); 
} 

}

like image 602
Raghav Kukreja Avatar asked Mar 11 '15 09:03

Raghav Kukreja


1 Answers

A little late but I just fixed this exact problem on my app. There are two solutions.

1) You have to use a FragmentStatePagerAdapter rather than a FragmentPagerAdapter

Or

2) If your ViewPager is wrapped in a Fragment (like your image shows), then when you create the ViewPager's adapter, you have to use getChildFragmentManager() rather than getSupportFragmentManager().

Hope this helps someone out as this took me an entire day of torture to figure this out.

like image 173
David Velasquez Avatar answered Oct 24 '22 04:10

David Velasquez