Friday, 13 January 2017

Android Sliding Tab - How To Open A Specific Tab

In several developers (Especially those who newbie in android ), in other case, sliding Tab will bring a difficulty  condition. One of the difficult situation is when they try to open a specific tab.

There are a lot of ways to do this. One of the simple way is using SharedPreferences. SharedPreferences will save the last index of tab that opened. When user open the activity when the sliding tab was placed, sharedPreference will retrieve the index that stored, then that index will matched with index of tab's item.

I hope you understand the explanation above, sorry for a worst english that i use. hahaha.

Okay for the detail, let's start the coding ....

I using THIS PROJECT to implementing how to open specific tab. But you can straight do in your project.

What should you do in your Fragment or on page where you start open the tab?

In every fragment, you have to store its index on sharedPreferences. Because later, that index will be leads you to open specific tab/fragment.

For example do this on your Fragment :

Case in this project : If i press the button, then the application will refresh the activity, but still open the current tab/fragment, get it?

What should you do in your Activity or on page where you hosting you sliding tab?

The activity that i mean is page where you hosting your sliding tab. Inside your onCreate() do like the following code :

In code above, the sharedPreference will retrieve the index that has stored from the specific fragment.

If SharedPreference contains null, the application will open the default tab. But if SharedPreference contains index, then the tab will opening according with the index.

What should you do after the application closed (user close the application) or if the page where you hosting the sliding tab is leaved?

It depend to you application requirements. If your apps need open the last tab that opened by user, then you don't need to do anything anymore, because the code above will open the last tab that opened by user.

But, if your apps required to open the default tab after user close the application, then you have to add a little bit code in your onDestroy() method :

That means, when the application closed by user, sharedpreference will store the default index, that is = 1. Done! I hope you guys understand what i said above. Good luck!