Create Tab Layout
Create a tab layout on Android
What is Tab Layout
I was working on a tabbed screen for saved offers. See below for screenshot.

Create The Layout
The entire offer screen is a Fragment. What I did is to include a Tab Layout in layout .xml file. Added the following code into the top of the fragment layout file.
1 | <android.support.design.widget.TabLayout |
You can visit the TabLayout page for more details.
Add Tab Items Programmatically
You can either add tab items in Layout file or create tab items programatically.
To create tab items programatically, you will first need to assign an ID to TabLayout so that you can get the TabLayout in Fragment.
1 | final TabLayout tabLayout = view.findViewById(R.id.deal_tab_main); |
Tab Tapped
When user tap on a tab, there are two things you can do. One thing is to switch to a different fragment. The other is to reload data for the current fragment. For us, I choose to reload the offer list.
If you want to switch to a different fragment, check ViewPager .
If you want to reload data when select another tab, use the OnTabSelectedListener. See below for the actual code.
1 | tabLayout.addOnTabSelectedListener(new OnTabSelectedListener() { |
Dynamically Create Tab Layout Using Enum
I end up using a enum for creating the tab. I add tab items programatically depending on items in an enum. So this is what I did.
First, put the enum somewhere:
1 | public enum DealsShowType { |
Then, create the tab items dynamically depending on the DealsShowType enums:
1 | final TabLayout tabLayout = view.findViewById(R.id.deal_tab_main); |
Last but not least, refresh data when tab gets pressed.
1 | tabLayout.addOnTabSelectedListener(new OnTabSelectedListener() { |
