Android Design Support Library made our day easier by providing backward compatibility to number of material design components all the way back to Android 2.1. In Design support Library the components like navigation drawer, floating action button, snackbar, tabs, floating labels and animation frameworks were introduced. In this article we are going to learn how to implement material tabs in your apps.
Before going further, I suggest have a look at this tabs docs that defines do’s and don’ts while implementing tabs.
1. Making the App Material
We’ll start this by creating a new project and applying the material theme. If you are not aware of android material design, my previous article Android Getting Started with Material Design gives you a good start.
1. In Android Studio, go to File ⇒ New Project and fill all the details required to create a new project. When it prompts to select a default activity, select Blank Activity and proceed.
2. Open build.gradle and add android design support library com.android.support:design:27.1.1 or the latest one.
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support:design:27.1.0' }
3. Open colors.xml located under res ⇒ values and add the below color values.
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#125688</color> <color name="colorPrimaryDark">#125688</color> <color name="textColorPrimary">#FFFFFF</color> <color name="windowBackground">#FFFFFF</color> <color name="navigationBarColor">#000000</color> <color name="colorAccent">#c8e8ff</color> </resources>
4. Add the below dimensions to dimens.xml located under res ⇒ values.
<resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> <dimen name="tab_max_width">264dp</dimen> <dimen name="tab_padding_bottom">16dp</dimen> <dimen name="tab_label">14sp</dimen> <dimen name="custom_tab_layout_height">72dp</dimen> </resources>
5. Open styles.xml located under res ⇒ values and add below styles. The styles defined in this styles.xml are common to all the android versions.
<resources> <style name="MyMaterialTheme" parent="MyMaterialTheme.Base"> </style> <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="windowNoTitle">true</item> <item name="windowActionBar">false</item> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
6. Now under res, create a folder named values-v21. Inside values-v21, create another styles.xml with the below styles. These styles are specific to Android 5.0
<resources> <style name="MyMaterialTheme" parent="MyMaterialTheme.Base"> <item name="android:windowContentTransitions">true</item> <item name="android:windowAllowEnterTransitionOverlap">true</item> <item name="android:windowAllowReturnTransitionOverlap">true</item> <item name="android:windowSharedElementEnterTransition">@android:transition/move</item> <item name="android:windowSharedElementExitTransition">@android:transition/move</item> </style> </resources>
7. Finally open AndroidManifest.xml and modify the theme to our customized theme by changing the android:theme attribute value.
android:theme="@style/MyMaterialTheme"
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="info.androidhive.materialtabs" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/MyMaterialTheme" > <activity android:name=".activity.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Run the app and verify the material theme by observing the notification bar color. If you see the notification bar color changed, it means that the material design theme is applied successfully.
Now we have our app material ready. So let’s start adding the tabs. But before that we’ll create few fragment activities for testing purpose. All these fragment activities contains very simple UI with only one TextView.
8. Under your main package create a fragment named OneFragment.java and add the below code.
package info.androidhive.materialtabs.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import info.androidhive.materialtabs.R; public class OneFragment extends Fragment{ public OneFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_one, container, false); } }
9. Open fragment_one.xml located under res ⇒ layout and do the below changes.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="info.androidhive.materialtabs.fragments.OneFragment"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/one" android:textSize="40dp" android:textStyle="bold" android:layout_centerInParent="true"/> </RelativeLayout>
10. Likewise create few more fragment activities with same code we used for OneFragment.java. I have created TwoFragment.java, ThreeFragment.java, FourFragemnt.java ….. upto TenFragment.java
2. Fixed Tabs
Fixed tabs should be used when you have limited number of tabs. These tabs are fixed in position. In android design support library lot of new elements like CoordinatorLayout, AppBarLayout, TabLayout and lot more were introduced. I won’t cover all of these as it’s not the agenda of this article.
11. Open the layout file of main activity (activity_main.xml) and add below layout code.
app:tabMode – Defines the mode of the tab layout. In our case the value should be “fixed”
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="fixed" app:tabGravity="fill"/> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout>
12. Open MainActivity.java and do the below changes.
tabLayout.setupWithViewPager() – Assigns the ViewPager to TabLayout.
setupViewPager() – Defines the number of tabs by setting appropriate fragment and tab name.
ViewPagerAdapter – Custom adapter class provides fragments required for the view pager.
package info.androidhive.materialtabs.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.List; import info.androidhive.materialtabs.R; import info.androidhive.materialtabs.fragments.OneFragment; import info.androidhive.materialtabs.fragments.ThreeFragment; import info.androidhive.materialtabs.fragments.TwoFragment; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new OneFragment(), "ONE"); adapter.addFragment(new TwoFragment(), "TWO"); adapter.addFragment(new ThreeFragment(), "THREE"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } }
Now run the app. You should able to see the tabs displayed with swipe functionality between the tabs.
2.1 Full Width Tabs
If you want the tabs to be occupied the fullwidth of the screen, you need to assign app:tabGravity=”fill” to our TabLayout.
2.2 Center Aligned Tabs
If you want to keep your tabs horizontally centered, assign app:tabGravity=”center” to TabLayout.
3. Scrollable Tabs
The scrollable tabs should be used when you have many number of tabs where there is insufficient space on the screen to fit all of them. To make the tabs scrollable, set app:tabMode=”scrollable” to TabLayout.
13. Open activity_main.xml and change the app:tabMode to scrollable.
<android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="scrollable"/>
14. Edit MainActivity.java and add few fragments to ViewPager in setupViewPager() method. I have added total of 10 fragments to ViewPager. After the changes, your main activity should look like below.
package info.androidhive.materialtabs.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFrag(new OneFragment(), "ONE"); adapter.addFrag(new TwoFragment(), "TWO"); adapter.addFrag(new ThreeFragment(), "THREE"); adapter.addFrag(new FourFragment(), "FOUR"); adapter.addFrag(new FiveFragment(), "FIVE"); adapter.addFrag(new SixFragment(), "SIX"); adapter.addFrag(new SevenFragment(), "SEVEN"); adapter.addFrag(new EightFragment(), "EIGHT"); adapter.addFrag(new NineFragment(), "NINE"); adapter.addFrag(new TenFragment(), "TEN"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFrag(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } }
Now if you run the app, you can see the more number of tabs with scrollable functionality.
4. Tabs with Icon & Text
Sometimes you might wanted to add an icon to Tab. Earlier adding an icon to tab is tedious process. But with the design support library it is very easy. All you have to do is call setIcon() method by passing appropriate icon. The icon will be placed in front of tab label.
tabLayout.getTabAt(0).setIcon(tabIcons[0]); tabLayout.getTabAt(1).setIcon(tabIcons[1]);
15. Open your MainActivity.java and modify the code as below. Here I have added a new method called setupTabIcons() in which I have set all the tab icons.
import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; private int[] tabIcons = { R.drawable.ic_tab_favourite, R.drawable.ic_tab_call, R.drawable.ic_tab_contacts }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); setupTabIcons(); } private void setupTabIcons() { tabLayout.getTabAt(0).setIcon(tabIcons[0]); tabLayout.getTabAt(1).setIcon(tabIcons[1]); tabLayout.getTabAt(2).setIcon(tabIcons[2]); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFrag(new OneFragment(), "ONE"); adapter.addFrag(new TwoFragment(), "TWO"); adapter.addFrag(new ThreeFragment(), "THREE"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFrag(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } }
5. Tabs with only Icons
Setting only icon to tab is same as setting text and icon except the method getPageTitle() in ViewPagerAdapter class returns null instead of tab label.
16. Open MainActivity.java and modify the getPageTitle() method as below and run the project.
@Override public CharSequence getPageTitle(int position) { // return null to display only the icon return null; }
6. Custom Tab View with Icon & Text
Setting a custom view to the tab is very useful when you are not able to achieve desired output by following the methods provided by tab layout. While setting a custom view to tab, make sure that you follow the specs suggested by android for tabs.
When we set the tab an icon and text, you can see the icon is horizontally aligned with tab text. But if you want to place the icon above the tab label, you have to use a custom view to achive it.
17. Under res ⇒ values, create an xml file named fonts.xml and add below string value. This xml file defines the font family for the tab label.
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="font_fontFamily_medium">sans-serif</string> </resources>
18. Under res ⇒ values-v21, create another xml named fonts.xml.
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="font_fontFamily_medium">sans-serif-medium</string> </resources>
19. Open activity_main.xml and set the custom height to TabLayout. Setting this height is important as placing icon above the tab label takes more space than normal.
<android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="@dimen/custom_tab_layout_height" app:tabMode="fixed" app:tabGravity="fill"/>
20. Create an xml layout named custom_tab.xml under res ⇒ layout. In this layout we have defined the custom view for the tab.
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tab" android:textColor="@color/colorAccent" android:textSize="@dimen/tab_label" android:fontFamily="@string/font_fontFamily_medium"/>
21. Open MainActivity.java and modify the code as below. Here if you observe setupTabIcons() method, I have rendered custom_tab.xml layout in each tab using below lines of code.
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabOne.setText("ONE"); tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0); tabLayout.getTabAt(0).setCustomView(tabOne);
import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import info.androidhive.materialtabs.R; import info.androidhive.materialtabs.fragments.OneFragment; import info.androidhive.materialtabs.fragments.ThreeFragment; import info.androidhive.materialtabs.fragments.TwoFragment; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; private int[] tabIcons = { R.drawable.ic_tab_favourite, R.drawable.ic_tab_call, R.drawable.ic_tab_contacts }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); setupTabIcons(); } private void setupTabIcons() { TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabOne.setText("ONE"); tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0); tabLayout.getTabAt(0).setCustomView(tabOne); TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabTwo.setText("TWO"); tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_call, 0, 0); tabLayout.getTabAt(1).setCustomView(tabTwo); TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabThree.setText("THREE"); tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_contacts, 0, 0); tabLayout.getTabAt(2).setCustomView(tabThree); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFrag(new OneFragment(), "ONE"); adapter.addFrag(new TwoFragment(), "TWO"); adapter.addFrag(new ThreeFragment(), "THREE"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFrag(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } }
Now if you run the app, you can see the icon placed above the tab label.
I hope this article provided useful information about the tab layout using design support library. If you have any queries please do comment below.
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
Thank you Ravi! You always rule!
Thanks Akkis 🙂
Plz Add at least one project on Widgets , Your posts are easy to understand Thank you !
Thanks for the suggestion.
followed you since 2012, still amazing.
Thank you Adi 🙂
Awesome Ravi keep it up.
Thanx Ravi for this awesome work. Keep up the hard work.
Will it possible for you to do a tutorial on responsive android design for different screen size, tablet and as well landscape!?
Noted 🙂
thank you Ravi always awesome work
Thank you so much 🙂
THANK YOU lecture , can i use old android api such as 2.3, and also used like navigation drawer action bar and fragment old android thanks
Yes, you can. Check this article
http://android-developers.blogspot.in/2015/05/android-design-support-library.html
great, thanks from argentina
hi Ravi, i want to subscribe you but your website does not send verifying email to me
Please use facebook login for subscribing.
Thank you Ravi . but download code not work.
Are you getting any error?
I also try to download the code and while I enter my email address, I never receive the confirmation email.
Pls use facebook login. Right now amazon email server is down and can’t be solved easily.
Ok. I did login with FB but FYI the problem with “regular” login is there for a couple of weeks. I remember I was trying to download some of your code weeks ago with the same login problem.
Yeah, my Amazon SES account is blocked due to too many spam email address.
Hi… i’m new to Android… and following your tutorial.. i’m unable to use “TabLayout”… it shows no class exist.
Did you added the design support library in build.gradle?
Yes i’ve added that…
Okay. Can you give me exact error message.
Done…!!
Actually there was a gradle sync error…!!
P.S – Your work is very cool..!!
Thanxxx
Okay. After adding something in build, you need to rebuild the project 🙂
Hi.. i’m doing same what you have described, my scroll functionality is working.. but i’m unable to tap on tabs..!
Only scroll is working… taps not responding on touch!
You have to add the design support library to your build.gradle and rebuid the project
I’ve done that… Now my tabs are visible i can scroll through them but i’m unable to access them by tapping… only scroll is working..!
Thank you Ravi…
Pls add a project for all the amazing features of android design support library like floating labels for editing text, floating action button, snackbar, collapsing toolbars etc…..your tutorials are awesome…
Yeah I started preparing one by one but got occupied with other work.
keep going your the best forever
tabs with icons…#guru
Thank you Ravi! You always rule!
You are welcome 😀
Hello Ravi…
Tutorials can’t be so much easy than this…
I was able to create Scrollable tabs…
but i am having problem in setting webview in onefragment.xml
i have set permissions right in androidmanifest…
i am successfully able to set webview in blank activity project but unable to get it working in your scrollable tabs project
if you can help me with some webview code
hi ravi i need help for ur side i need to set the default alarms for different timings if you can help me with some alarm code
HI Ravi,i need one help from u… how to handle back button in fragment
Hi Ravi! In case of custom view icon & text, I have a listview in view for two fragments. But1.5 rows of that listview is hiding behind the toolbar. Can you help me with this ?
Yeah, I have seen this problem but couldn’t get solution to it. Temporarily you can add margin top to your ListView equal to toolbar height.
me too did the same solution. So where do you work and from how many years you are working on android?
I am a full time blogger and freelancer. I have 4yrs of experience in Android. Check my other skills here 🙂
http://in.linkedin.com/pub/ravi-tamada/26/457/a12
Thanks for sharing . . . you have a great passion for android. I liked your tutorial, they are so easy to understand and implement. Will be implementing all your examples soon. You are learning all this by your own?
Yes, I learn by my own. I mostly read android docs.
I actually ran into the same issue but the
android:layout_margintop=”?attr/actionBarSize” presented many other issues. Eventually I found that adding
app:layout_behavior=”@string/appbar_scrolling_view_behavior”
to the view pager did the trick… Hopefully this will save someone hours of trial and errors
Cool.
“app:layout_behavior=”@string/appbar_scrolling_view_behavior”
did not work for me!
The Listview is still missing the last row, it is hidden.
Image:
Does anyone know how to fix this?
Hi Ravi , Thx for lesson was help me .
Use below attribute to your ViewPager.
app:layout_behavior=”@string/appbar_scrolling_view_behavior”
worked nicely!! Thanks man.
hi Ravi,awesome tutorial,please i want to be able to scroll the tabs by tapping the respective header or text without swiping,(Like BBM) please how do i achieve that..thanks
Hey Ravi, how do i invoke the back button on the action bar?
If you want to see the back arrow in action bar, you have to add android:parentActivityName=”” to the activity.
To be notified whenever user presses the back button, add the below code in your activity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar’s Up/Home button
case android.R.id.home:
// write your code here
return true;
}
return super.onOptionsItemSelected(item);
}
Mr Ravi please how to make the tab icons move the tabs without necessarily swiping the tabs
Can you explain your query detailed?
for some reason i cant explain,when i click on the tab icons,the tabs do not move,even the action bar icons cannot be clicked,more like the whole screen is the Viewpager
But i changed
to just a RelativeVIew and it works fine.
what could be wrong please? or do i just stick to the RelativeView
In Main_Activity.xml
put “ViewPager” code into “AppBarLayout” .
It will work…
<android.support.design.widget.AppBarLayout
…
…
@Ravi Tamada:disqus your work is really good…!
Thank you Rahul 🙂
Ravi, great article, helped me a lot.
Hello Ravi, Thanks for tutorial.
I have a question, How to replace Theme or color of toolbar and status bar when click in another tab.
if you can explain to the TabActivity no in Fragment.
Thanks.
As of now dynamic theme switching is not supported.
Hi, Ravi
Thanks For the tutorial, its very helpful to me.
I’m getting error in the values–>styles–> true
Hi @Ravi Tamada
I have been trying to combine this new MaterialTabSlids and the other MaterialDesign Drawer like i did the other time but this one seems a bit twisted as i keep getting error from “NavigationDrawerAdapter” on this code line
adapter = new NavigationDrawerAdapter(getActivity(), getData());
ERROR MESSAGE::
‘NavigationDrawerAdapter(android.content.Context, java.util.List)’ in ‘okechukwu.com.materialtab.adapter.NavigationDrawerAdapter’ cannot be applied to ‘(android.support.v4.app.FragmentActivity, java.util.List)’
its really crappy for me to combine this time. WOuld appreciate if you can make it happen this time or direct me on how to go about it.
Sometime we unknowingly import two different packages. FragmentActivity can be imported using two diff packages.
android.app.FragmentActivity
or
android.support.v4.app.FragmentActivity
Make sure that you are importing same package in both classes. I suggest use android.support.v4.app.FragmentActivity in both the classes.
I am using eclipse and i got the following error …
java.lang.NoClassDefFoundError: android.support.v7.app.AppCompatDelegateImplV14…
how to resolve this
Simple, move to Android Studio. I should stop supporting Eclipse.
Hello again Ravi!
Do you know a way to swap fragments? Lets say there is a button on my first tab’s fragment and when I click on that button I want to change the first tab’s fragment to fragment four.
Also, is there any way I can donate to your page? You helped me a lot with all the tutorials you have posted and I wish I can repay that!
You can do that creating a listener interfaces between the fragments
http://developer.android.com/intl/zh-tw/training/basics/fragments/communicating.html
I don’t have any donation button. I earn enough money from advertisements. Thanks for your concern though 😀
Not sure if I placed my code correctly or i am just confused. Have you tried it yourself yet? Because it doesn’t work on mine
* Hi Ravi. First, I want to say you did a great Job. It is a very detailed and useful tutorial. I have downloaded source code and applied into my own project.
* Everything is great except one problem. Tabs don’t show full of my activities. They clipped the layout. I uploaded a picture of what I mean:
How to fix this problem? If you help, i Will be gratefull to you.
Ravi already answered this below
Use below attribute to your ViewPager.
app:layout_behavior=”@string/appbar_scrolling_view_behavior”
Yeah, I have updated the code now.
tuturial awesome, but i have problem that i have 3 fragment, when i unselect a tab and when back to that tab , it reload again ( i get data form Internet). so can i do repair it?
I think you should play with show() and hide() instead of replace(). http://developer.android.com/reference/android/app/FragmentTransaction.html
Try this one (I haven’t tested)
http://stackoverflow.com/questions/28494637/android-how-to-stop-refreshing-fragments-on-tab-change
I am expecting a good tutorial about Gradle and some cool things we can done using it. Will you make a tutorial about them ? Pleasee 🙂
Hi Ravi, awesome article for a new comer like me. I need to integrate tabbed layout inside fragments since I am using navigation drawer using your other article. Now i need to create Tab fragments inside each of the drawer fragments. Can you guide me on what to do? Thanks
Hey mate, I have implemented the TabLayout inside a Fragment cause my App is implemented Navigation Drawer also. Working fine on 5.0 and above but TabLayout is not showing on 4.4 devices. What could be the problem. Please help.
Are you testing on read device or emulator?
I am testing it on real devices:
Galaxy S5 with 5.0
Galaxy Grand Prime with 4.4
Hello Ravi,
Learning Android programming from your website is a very unique experience 🙂 You’ve actually helped me a lot with your tutorials and there’s something I’d like to ask.
I finished this tutorial but I have no idea how to customize the contents of these fragments. I cannot change anything. How can I do it? What should I learn to be able to do this? Can you give a little information about this issue? 🙂 I’m planning to add some cards and filling them with the data from my database with JSON. But for now, I cannot even change the default texts inside the fragments :))
Your help will be very appreciated 🙂
Thank you very much!
Fragments are not much different from android except their life cycle methods varies.
In Activity we set layout in onCreate() method. In fragments we set the layout in onCreateView() method.
In this article you have to do the modifications in fragment_one.xml to see the changes in the layout.
Learn about fragments here
http://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/
Thank you very much for your response!!!
You are welcome 🙂
Hi Ravi
it’s a great tutorial , but there is a problem ” You need to use a Theme.AppCompat theme (or descendant) with this activity.”
i tried many solution for this , but the same error appears every time …
Can you post the complete error log.
i Ravi, Its so awesome tutorial. Can you tell me how to change color icon, text color when icon tabs selected (CustomViewIconTextTabsActivity)..?
Listview problem: The last row is missing, because it is outside of the screen.
“app:layout_behavior=”@string/appbar_scrolling_view_behavior” did not help me.
I have an image:
Can anyone help me please. I have followed the guide and other similar guides, but the Viewpager is too long.
If you have added marginTop to ListView, remove that attribute.
Hi Ravi, Can you tell me how to add com.android.support:design:23.0.1 library in eclipse. I am not able to run this project in eclipse having lot of issues. But i managed some issue. I am keep getting this error “error: No resource identifier found for attribute ‘layout_scrollFlags’ in package ‘tab.android.tabsample'” in activity_custom_view_icon_text_tabs.xml layout. Please help me in solving this issue. I just copied all layout, styles from your sample code and pasted it in my sample app. Copied the package into my sample app the same way. I imported all the package name correctly in .Java file. Need help
Move to Android Studio. In Android Studio you can directly import the Eclipse project. It won’t take more than 2mins.
Awsome Tutorial … Please can u upload a tutorial sample how to use drawer layout and sliding tabs combined together?
First follow below tutorial and integrate tabs into it.
http://www.androidhive.info/2015/04/android-getting-started-with-material-design/
I want different tabs for each drawer item … So I am a bit confused here … and also want to show nd hide actionbar on slide like google playstore? please help me
I have successfully added total of 5 tabs in icon and text activity by changing the tabmode to gravity in activity_icon_text_tab.xml and adding adapter.addFrag to IconTextTabActivity
but i am unable to add icons to new tabs
here what i have done in IconTextTabsActivity class
private int[] tabIcons = {
R.drawable.ic_tab_favourite,
R.drawable.ic_tab_call,
R.drawable.ic_tab_contacts,
R.drawable.ic_action_name,
R.drawable.ic_action_sms
};
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(4).setIcon(tabIcons[4]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new OneFragment(), “Home”);
adapter.addFrag(new TwoFragment(), “CHAT”);
adapter.addFrag(new ThreeFragment(), “Call”);
adapter.addFrag(new FourFragment(), “Sms”);
adapter.addFrag(new FiveFragment(), “About”);
viewPager.setAdapter(adapter);
}
Pls paste the complete of the activity.
Hey Ravi, great work with the tutorials… I’m having an issue though… In Android Device (Galaxy S6), the tabs can be clicked or swiped but in Android 4.4 (Galaxy S4 mini), just the swipe works.. Not even the ripple effect is reproduced on 4.4..
Can this still be done using eclipse? :/ men, i did not see this. This is much better than the tab layout with swipeable views
The best! Great tnx!
You are welcome 🙂
We have Implemented your code it’s awesome but we found one bug when we Start swipe First-Tab then Second-Tab is Visible but Third tab onStart() method call when we start swipe Second then Third-tab is Visible but Fourth-Tab onStart() method call please tell me why this happened
Thank you Ravi. Nice Tutorial
Hi Ravi
Your tutorials are very helpful for me ,as a beginner iam in trouble with the following code ..
imports :
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’.
> Compilation failed; see the compiler error output for details.
Error:(28, 9) error: cannot find symbol method setupViewPager(ViewPager)
Created Fragment and imports :
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
dependencies :
compile fileTree(dir: ‘libs’, include: [‘*.jar’])
compile ‘com.android.support:appcompat-v7:23.0.1’
compile ‘com.android.support:design:23.0.1’
compile ‘com.android.support:support-v4:23.0.1’
android {
compileSdkVersion 23
buildToolsVersion ‘23.0.1’
defaultConfig {
applicationId “com.example.junaidkodoor.material_designing”
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName “1.0”
}
buildTypes {
Hi ravi
Your tutorials are very useful for me ,As a begginer am in trouble with folloing errors :
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
Actual code :
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.example.junaidkodoor.material_designing.R;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
Also Created Fragments coade as below:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.junaidkodoor.material_designing.R;
/**
* Created by junaidkodoor on 27/9/15.
*/
public class OneFragment extends Fragment {
public OneFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
Dependencies :
android {
compileSdkVersion 23
buildToolsVersion ‘23.0.1’
defaultConfig {
applicationId “com.example.junaidkodoor.material_designing”
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName “1.0”
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’
}
}
}
dependencies {
compile fileTree(dir: ‘libs’, include: [‘*.jar’])
compile ‘com.android.support:appcompat-v7:23.0.1’
compile ‘com.android.support:design:23.0.1’
compile ‘com.android.support:support-v4:23.0.1’
}
Hi ravi
i have a following error in a example
01-12 06:16:02.577: E/AndroidRuntime(14160): FATAL EXCEPTION: main
01-12 06:16:02.577: E/AndroidRuntime(14160): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.materialtabs/info.androidhive.materialtabs.activity.MainActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class android.support.design.widget.CoordinatorLayout
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.access$600(ActivityThread.java:162)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.os.Handler.dispatchMessage(Handler.java:107)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.os.Looper.loop(Looper.java:194)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.main(ActivityThread.java:5371)
01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Method.invokeNative(Native Method)
01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Method.invoke(Method.java:525)
01-12 06:16:02.577: E/AndroidRuntime(14160): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
01-12 06:16:02.577: E/AndroidRuntime(14160): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
01-12 06:16:02.577: E/AndroidRuntime(14160): at dalvik.system.NativeStart.main(Native Method)
01-12 06:16:02.577: E/AndroidRuntime(14160): Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class android.support.design.widget.CoordinatorLayout
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.createView(LayoutInflater.java:613)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
01-12 06:16:02.577: E/AndroidRuntime(14160): at info.androidhive.materialtabs.activity.MainActivity.onCreate(MainActivity.java:20)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.Activity.performCreate(Activity.java:5122)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
01-12 06:16:02.577: E/AndroidRuntime(14160): … 11 more
01-12 06:16:02.577: E/AndroidRuntime(14160): Caused by: java.lang.reflect.InvocationTargetException
01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Constructor.constructNative(Native Method)
01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.createView(LayoutInflater.java:587)
01-12 06:16:02.577: E/AndroidRuntime(14160): … 21 more
01-12 06:16:02.577: E/AndroidRuntime(14160): Caused by: java.lang.NoClassDefFoundError: android.support.design.R$styleable
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:171)
01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:165)
01-12 06:16:02.577: E/AndroidRuntime(14160): … 24 more
Parag, I found the solution
Problem what i faced is R.Java file is not generated under support.design in gen/ folder. After doing the below steps R.Java file is generated. Main issue is “design” library is target to 22. Changing to 23 worked.
1. Import support design library from sdkextrasandroidsupportdesign to eclipse workspace.
2. Open project.properties of AppCompat and design Library and target it to 23
3. Clean Appcompat, design and YourTabProject.
4. Now every things goes good.
Don’t we need to implement OnFragmentInteractionListener interface in MainActivity? I got an exception that showed that I need these implements from every fragments. I implemented those and it worked
We have Implemented your code it’s awesome but we found one bug when we
Start swipe First-Tab then Second-Tab is Visible but Third tab onStart()
method call when we start swipe Second then Third-tab is Visible but
Fourth-Tab onStart() method call please tell me why this happened
Hi Ravi,
I followed this blog and create a new project in eclipse using your sample source code. I am not getting any error in code. But during running the app i am getting an error on run time of the app. Please look into this question http://stackoverflow.com/questions/32838594/error-inflating-class-android-support-design-widget-coordinatorlayout-and-classn and help me. I am trying to solve this error from day before yesterday, nothing worked for me. Please help me.
Hi Ravi,
Scrollable tab is not working. I am seeing the Tab name as O, T, T, F..N,T instead of One, Two …Ten. While loading it shows as One, Two …Ten and after few seconds the Tab name become O, T, T, F..N,T and completely fit inside the screen. It is showing the first letter of Tab name and srink inside the screen. No option to scroll.
app:tabMode=”scrollable” is already there in activity_scrollable_tab.xml
Please help me in solve this.
Just add in your activity onCreate method below getting tabLayout reference
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);