ALi Hamza
ALi Hamza

Reputation: 17

how to store state of pager view with screen rotation

i want to add screen rotation support to the activity having a pager view. what i want is when user changes screen orientation, the tab of pager view that was open should be opened in the new orientation. but now activity restarts and every time first tab opens. kindly help me . Thanks in Advance.

package com.example.ali.namallibrary;
import android.app.Fragment;
import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.Serializable;

public class aboutLibrary extends AppCompatActivity {

CustomAdapter customAdapterpter = null;
TabLayout tabLayout;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about_library);
    customAdapterpter  = new CustomAdapter(getSupportFragmentManager(),getApplicationContext());

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    viewPager.setAdapter(customAdapterpter);

    tabLayout = (TabLayout) findViewById(R.id.tabBar);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()   {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }
    });
} // end of oncreate

private class CustomAdapter extends FragmentPagerAdapter {
    private String[] fragmentNames = {"About","Collection","Timing","Contact"};
    public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
        super(supportFragmentManager);
    }
    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        switch (position)
        {
            case 0 :
                return new aboutLibraryFrag();
            case 1 :
                return new libraryCollectionFrag();
            case 2 :
                return new libraryTimingFrag();
            case 3 :
                return new contactUsFrag();
            default:
                return null;
        }
    }
    @Override
    public int getCount() {
        return fragmentNames.length;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentNames[position];
    }
}

Upvotes: 0

Views: 1363

Answers (2)

Pierre
Pierre

Reputation: 9082

Another way to deal with screen changes and or rotation is to add android:configChanges to your activity:

<activity android:name="com.example.myactivity" 
          android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|uiMode" />

The ConfigChanges mentioned will not cause your activity to be detroyed and recreated when they occur instead, Android will simply rotate the screen and then call onConfigurationChanged where you can manually handle the cases yourself.

You can override onConfigurationChanged in your activity to handle the events.

public class myactivity extends Activity
{
    //..

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }
}

Read more in the Android documentation here

Upvotes: 1

Lyla
Lyla

Reputation: 2777

Whenever your rotate the screen, the activity is completely destroyed and re-created. To deal with this, there is a lifecycle method called onSaveInstanceState. In this method you can save a Bundle object. A Bundle is a bunch of key value pairs that you define, which you want around after the rotation. In that Bundle, you can store the current position of your view pager. I'm haven't worked much with ViewPagers, but getCurrentItem might be what you're looking for. You'd need to make your ViewPager a member variable, and a constant for the key. Then I'm guessing it would look something like:

public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(CURRENT_POSITION_KEY, mViewPager.getCurrentItem());

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

The onCreate method takes a Bundle savedInstanceState - if the activity is being restarted from a rotation, this parameter will have everything you saved in onSaveInstanceState. Thus you can do something like this in onCreate:

// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
 int currentPos = savedInstanceState.getInt(CURRENT_POSITION_KEY);
 mViewPager.setCurrentItem(currentPos)
}

More information about loading and saving the state between rotations can be found here: https://developer.android.com/guide/components/activities/activity-lifecycle.html#saras

Upvotes: 1

Related Questions