This is something I built into v2.0 of Pace Calculator, since often users would be only runners, cyclists or swimmers, and once they select a particular tab, they want the app to start-up in that tab every time. It uses the basic SharedPreferences object, all within the main activity that controls the ActionBarActivity tabs.

First, in MainActivity, set up the following variables

Integer tabPref;
SharedPreferences prefs;

In the onCreate method instantiate the variables, defaulting to 0 if the app has never been used before

prefs = getPreferences(Context.MODE_PRIVATE);
tabPref = prefs.getInt("tabPref", 0);

You need to make sure that when each tab is selected, the preference is also set, and editor.apply() called

mViewPager
		.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
				SharedPreferences.Editor editor = prefs.edit().putInt(
						"tabPref", position);
		 	    editor.apply();
		}
	});

Finally, at the end of OnCreate, you need to make sure that the tab determined in the preferences is selected with

mViewPager.setCurrentItem(tabPref, false);

That’s it!

Share this post
Tweet about this on TwitterShare on LinkedInShare on Google+Email this to someone

One thought on “Android: Remembering users previous tab selection

Leave a Reply

Your email address will not be published. Required fields are marked *