public class MainActivity extends FragmentActivity implements ActionBar.TabListener { private ViewPager viewPager; private TabsPagerAdapter mAdapter; private ActionBar actionBar; // Tab titles private String[] tabs = { “First Tab”, “Second Tab”, “Third Tab”, “Fourth Tab” }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initilization viewPager = (ViewPager) findViewById(R.id.pager); actionBar = getActionBar(); mAdapter = new TabsPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(mAdapter); actionBar.setHomeButtonEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Adding Tabs for (String tab_name : tabs) { actionBar.addTab(actionBar.newTab().setText(tab_name) .setTabListener(this)); } /** * on swiping the viewpager make respective tab selected * */ viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { // on changing the page // make respected tab selected actionBar.setSelectedNavigationItem(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // on tab selected // show respected fragment view viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { }
TabLayout tab selection
I was further facing a problem where some of the internal objects would return null (because they weren’t created yet, because I was answering onActivityResult() from my fragment, which occurs before onCreate() in the case the activity is singleTask or singleInstance ) so I wrote up a detailed if/else sequence which would report the error and fall through without the NullPointerException that would otherwise trigger.
Android TabLayout
TabLayout is released by Android after the deprecation of ActionBar.TabListener (API level 21). TabLayout is introduced in design support library to implement tabs. Tabs are created using newTab() method of TabLayout class. We can also add tab item to TabLayout using TabItem of android design widget.
Create an activity.xml file with TabLayout and ViewPager view components. package tablayout.example.com.tablayout; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { TabLayout tabLayout; ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout=(TabLayout)findViewById(R.id.tabLayout); viewPager=(ViewPager)findViewById(R.id.viewPager); tabLayout.addTab(tabLayout.newTab().setText(“Home”)); tabLayout.addTab(tabLayout.newTab().setText(“Sport”)); tabLayout.addTab(tabLayout.newTab().setText(“Movie”)); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(), tabLayout.getTabCount()); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } }
package tablayout.example.com.tablayout; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentManager; public class MyAdapter extends FragmentPagerAdapter { private Context myContext; int totalTabs; public MyAdapter(Context context, FragmentManager fm, int totalTabs) { super(fm); myContext = context; this.totalTabs = totalTabs; } // this is for fragment tabs @Override public Fragment getItem(int position) { switch (position) { case 0: HomeFragment homeFragment = new HomeFragment(); return homeFragment; case 1: SportFragment sportFragment = new SportFragment(); return sportFragment; case 2: MovieFragment movieFragment = new MovieFragment(); return movieFragment; default: return null; } } // this counts total number of tabs @Override public int getCount() { return totalTabs; } }
TabLayout Tutorial With Example In Android Studio
In Android TabLayout is a new element introduced in Design Support library. TabLayout is basically view class required to be added into our layout(xml) for creating Sliding Tabs. We use different methods of TabLayout to create, add and manage the tabs. Special Note: TabLayout is used to display tabs on the screen.
Below we firstly create a new tab and then add it in the TabLayout and set the true value for setSelected parameter that makes it selectable. Below we firstly create a new tab and then add it in the TabLayout at a specific position. This method returns an int type value for the position of the selected tab. 8. getTabCount(): This method is used to get the number of tabs currently registered with the action bar. This method returns an int type value for the number of total tabs. Below we get the total number of tabs currently registered with the action bar. 10. getTabGravity(): This method is used to get the current gravity used for laying out tabs. They are best used for browsing contexts in touch interfaces when users don’t need to directly compare the tab labels.
14. getTabTextColors(): This method is used to get the text colors for the different states (normal, selected) of the tabs. Below we firstly create and add a tab and then remove it from the TabLayout. 18. removeTabAt(int position): This method is used to remove a tab from the layout. In this method we pass the position of the tab that we want to remove from the layout.
Now let’s we discuss some common attributes of a TabLayout that helps us to configure it in our layout (xml). 4. support.design:tabIndicatorColor: This attribute is used to set the Color of the indicator used to show the currently selected tab.
5. support.design:tabIndicatorHeight: This attribute is used to set the height of the indicator used to show the currently selected tab. 8. support.design:tabMode: This attribute is used to set the behavior mode for the Tabs in this layout. android.support.design:tabPaddingBottom: Set padding along the bottom edge of the tabs.
android.support.design:tabPaddingStart: Set padding along the start edge of the tabs.
10. support.design:tabSelectedTextColor: This attribute is used to set the text color to be applied to the currently selected tab. 11. support.design:tabTextColor: This method is used to set the default text color to be applied to tabs. . We can also set this programmatically using setTabTextColors(int normalColor, int selectedColor) method.
After that we implement setOnTabSelectedListener event and replace the FrameLayout with the fragment’s according to selected tab. Step 2: Open build.gradle and add Design support library dependency. apply plugin: ‘com.android.application’ android { compileSdkVersion 23 buildToolsVersion “23.0.2” defaultConfig { applicationId “com.abhiandroid.tablayoutexample” 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.1.0’ compile ‘com.android.support:design:23.1.0’ // design support library }
Step 3: Open res -> layout ->activity_main.xml (or) main.xml and add following code:
In this step we add the code for displaying TabLayout and ViewPager in our xml file. In this step we open MainActivity and add the code for initiate the FrameLayout and TabLayout.
Finally we implement setOnTabSelectedListener event and replace the FrameLayout with the fragment’s according to selected tab. package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FirstFragment extends Fragment { public FirstFragment() { // 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_first, container, false); } }
package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SecondFragment extends Fragment { public SecondFragment() { // 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_second, container, false); } } package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ThirdFragment extends Fragment { public ThirdFragment() { // 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_third, container, false); } } Below is the example of TabLayout in which we display sliding tabs with the help of ViewPager. Step 2: Open build.gradle and add Design support library dependency.
apply plugin: ‘com.android.application’ android { compileSdkVersion 23 buildToolsVersion “23.0.2” defaultConfig { applicationId “com.abhiandroid.tablayoutexample” 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.1.0’ compile ‘com.android.support:design:23.1.0’ // design support library } Step 3: Open res -> layout ->activity_main.xml (or) main.xml and add following code:
In this step we open MainActivity and add the code for initiate the ViewPager and TabLayout. package com.abhiandroid.tablayoutexample; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; public class PagerAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; public PagerAdapter(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: FirstFragment tab1 = new FirstFragment(); return tab1; case 1: SecondFragment tab2 = new SecondFragment(); return tab2; case 2: ThirdFragment tab3 = new ThirdFragment(); return tab3; default: return null; } } @Override public int getCount() { return mNumOfTabs; } } package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FirstFragment extends Fragment { public FirstFragment() { // 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_first, container, false); } } package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SecondFragment extends Fragment { public SecondFragment() { // 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_second, container, false); } }
package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ThirdFragment extends Fragment { public ThirdFragment() { // 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_third, container, false); } }
Android Developers
A ViewPager.OnPageChangeListener class which contains the necessary calls back to the provided TabLayout so that the tab position is kept in sync. A TabLayout.OnTabSelectedListener class which contains the necessary calls back to the provided ViewPager so that the tab position is kept in sync. Constants int GRAVITY_CENTER Gravity used to lay out the tabs in the center of the TabLayout . int GRAVITY_START Gravity used to lay out the tabs aligned to the start of the TabLayout .
int INDICATOR_ANIMATION_MODE_FADE Indicator animation mode used to switch the selected tab indicator from one tab to another by sequentially fading it out from the current destination and in at its new destination. int TAB_LABEL_VISIBILITY_UNLABELED If a tab is instantiated with TabLayout.Tab.setText(CharSequence) , and this mode is set, the text will be saved and utilized for the content description, but no visible labels will be created.
Public methods void addOnTabSelectedListener(TabLayout.OnTabSelectedListener listener) Add a TabLayout.OnTabSelectedListener that will be invoked when tab selection changes. void addOnTabSelectedListener(BaseOnTabSelectedListener listener) This method is deprecated.
int getTabCount() Returns the number of tabs currently registered with the action bar.
ColorStateList getTabIconTint() Gets the icon tint for the different states (normal, selected) used for the tabs. ColorStateList getTabTextColors() Gets the text colors for the different states (normal, selected) used for the tabs. boolean isTabIndicatorFullWidth() Get whether or not selection indicator width is fit to full width of the tab item, or fit to the tab item’s content.
void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) boolean onInterceptTouchEvent(MotionEvent event) boolean onTouchEvent(MotionEvent event) void removeAllTabs() Remove all tabs from the action bar and deselect the current tab. void removeOnTabSelectedListener(TabLayout.OnTabSelectedListener listener) Remove the given TabLayout.OnTabSelectedListener that was previously added via addOnTabSelectedListener(OnTabSelectedListener) .
void removeOnTabSelectedListener(BaseOnTabSelectedListener listener) This method is deprecated.
void removeTabAt(int position) Remove a tab from the layout.
void setSelectedTabIndicator(Drawable tabSelectedIndicator) Sets the selection indicator for this TabLayout. void setSelectedTabIndicator(int tabSelectedIndicatorResourceId) Sets the drawable resource to use as the selection indicator for this TabLayout.
void setSelectedTabIndicatorHeight(int height) This method is deprecated. void setTabIconTint(ColorStateList iconTint) Sets the icon tint for the different states (normal, selected) used for the tabs.
void setTabIconTintResource(int iconTintResourceId) Sets the icon tint resource for the different states (normal, selected) used for the tabs.
void setTabIndicatorAnimationMode(int tabIndicatorAnimationMode) Set the mode by which the selection indicator should animate when moving between destinations. void setTabRippleColorResource(int tabRippleColorResourceId) Sets the ripple color resource for this TabLayout. void setTabTextColors(ColorStateList textColor) Sets the text colors for the different states (normal, selected) used for the tabs.
void setTabsFromPagerAdapter(PagerAdapter adapter) This method is deprecated. When that method is used, the TabLayout will be automatically updated when the PagerAdapter is changed. GRAVITY_CENTER public static final int GRAVITY_CENTER Gravity used to lay out the tabs in the center of the TabLayout .
GRAVITY_FILL public static final int GRAVITY_FILL Gravity used to fill the TabLayout as much as possible. This option only takes effect when used with MODE_FIXED on non-landscape screens less than 600dp wide. GRAVITY_START public static final int GRAVITY_START Gravity used to lay out the tabs aligned to the start of the TabLayout .
INDICATOR_ANIMATION_MODE_FADE public static final int INDICATOR_ANIMATION_MODE_FADE Indicator animation mode used to switch the selected tab indicator from one tab to another by sequentially fading it out from the current destination and in at its new destination. The left and right side of the selection indicator translate in step over the duration of the animation.
The only exception to this is when the indicator needs to change size to fit the width of its new destination tab’s label. This will only take effect if the indicator height is set via the custom indicator drawable’s intrinsic height (preferred), via the tabIndicatorHeight attribute (deprecated), or via setSelectedTabIndicatorHeight(int) (deprecated).
This will only take effect if the indicator height is set via the custom indicator drawable’s intrinsic height (preferred), via the tabIndicatorHeight attribute (deprecated), or via setSelectedTabIndicatorHeight(int) (deprecated). This will disregard tabIndicatorHeight and the indicator drawable’s intrinsic height, if set.
This will only take effect if the indicator height is set via the custom indicator drawable’s intrinsic height (preferred), via the tabIndicatorHeight attribute (deprecated), or via setSelectedTabIndicatorHeight(int) (deprecated). They are best used for browsing contexts in touch interfaces when users don’t need to directly compare the tab labels. TAB_LABEL_VISIBILITY_LABELED public static final int TAB_LABEL_VISIBILITY_LABELED This mode is set by default. If a tab is instantiated with TabLayout.Tab.setText(CharSequence) , a visible label will be created.
TAB_LABEL_VISIBILITY_UNLABELED public static final int TAB_LABEL_VISIBILITY_UNLABELED If a tab is instantiated with TabLayout.Tab.setText(CharSequence) , and this mode is set, the text will be saved and utilized for the content description, but no visible labels will be created. Components that add a listener should take care to remove it when finished via removeOnTabSelectedListener(OnTabSelectedListener) .
use addOnTabSelectedListener(OnTabSelectedListener) Add a TabLayout.BaseOnTabSelectedListener that will be invoked when tab selection changes. Components that add a listener should take care to remove it when finished via removeOnTabSelectedListener(BaseOnTabSelectedListener) .
addView public void addView (View child, int index) Parameters child View index int addView public void addView (View child, int index, ViewGroup.LayoutParams params) Parameters child View index int params ViewGroup.LayoutParams isTabIndicatorFullWidth public boolean isTabIndicatorFullWidth () Get whether or not selection indicator width is fit to full width of the tab item, or fit to the tab item’s content. Related XML Attributes: TabLayout_tabIndicatorFullWidth Returns boolean whether or not selection indicator width is fit to the full width of the tab item See also: setTabIndicatorFullWidth(boolean)
You need to manually add this using addTab(Tab) or a related method. use removeOnTabSelectedListener(OnTabSelectedListener) Remove the given TabLayout.BaseOnTabSelectedListener that was previously added via addOnTabSelectedListener(BaseOnTabSelectedListener) . Related XML Attributes: TabLayout_tabInlineLabel Parameters inline boolean See also: isInlineLabel()
Related XML Attributes: TabLayout_tabInlineLabel Parameters inlineResourceId int : Resource ID for boolean inline flag See also: isInlineLabel()
setScrollPosition public void setScrollPosition (int position, float positionOffset, boolean updateSelectedText, boolean updateIndicatorPosition) Set the scroll position of the tabs. Calling this method does not update the selected tab, it is only used for drawing purposes. Calling this method does not update the selected tab, it is only used for drawing purposes. If tabIndicatorColor is specified via the TabLayout’s style or via setSelectedTabIndicatorColor(int) the selection indicator will be tinted that color. If tabIndicatorColor is specified via the TabLayout’s style or via setSelectedTabIndicatorColor(int) the selection indicator will be tinted that color. Parameters tabSelectedIndicatorResourceId int : A drawable resource to use as the selected tab indicator. You must set the indicator height via the custom indicator drawable’s intrinsic height (preferred), via the tabIndicatorHeight attribute (deprecated), or via setSelectedTabIndicatorHeight(int) (deprecated). Related XML Attributes: TabLayout_tabIndicatorGravity Parameters indicatorGravity int : one of INDICATOR_GRAVITY_BOTTOM , INDICATOR_GRAVITY_CENTER , INDICATOR_GRAVITY_TOP , or INDICATOR_GRAVITY_STRETCH
setTabIconTintResource public void setTabIconTintResource (int iconTintResourceId) Sets the icon tint resource for the different states (normal, selected) used for the tabs. Parameters iconTintResourceId int : A color resource to use as icon tint. Related XML Attributes: TabLayout_tabIndicatorAnimationMode Parameters tabIndicatorAnimationMode int : one of INDICATOR_ANIMATION_MODE_LINEAR or INDICATOR_ANIMATION_MODE_ELASTIC See also: getTabIndicatorAnimationMode()
Related XML Attributes: TabLayout_tabIndicatorFullWidth Parameters tabIndicatorFullWidth boolean : Whether or not to fit selection indicator width to full width of the tab item See also: isTabIndicatorFullWidth()
They are best used for browsing contexts in touch interfaces when users don’t need to directly compare the tab labels. Related XML Attributes: TabLayout_tabMode Parameters mode int : one of MODE_FIXED or MODE_SCROLLABLE . When running on devices with KitKat or below, we draw this color as a filled overlay rather than a ripple. When running on devices with KitKat or below, we draw this color as a filled overlay rather than a ripple.
setTabTextColors public void setTabTextColors (int normalColor, int selectedColor) Sets the text colors for the different states (normal, selected) used for the tabs.
When that method is used, the TabLayout will be automatically updated when the PagerAdapter is changed. setUnboundedRipple public void setUnboundedRipple (boolean unboundedRipple) Set whether this TabLayout will have an unbounded ripple effect or if ripple will be bound to the tab item size. Related XML Attributes: TabLayout_tabUnboundedRipple Parameters unboundedRipple boolean See also: hasUnboundedRipple()
setUnboundedRippleResource public void setUnboundedRippleResource (int unboundedRippleResourceId) Set whether this TabLayout will have an unbounded ripple effect or if ripple will be bound to the tab item size. Related XML Attributes: TabLayout_tabUnboundedRipple Parameters unboundedRippleResourceId int : Resource ID for boolean unbounded ripple value See also: hasUnboundedRipple() This is the same as calling setupWithViewPager(ViewPager, boolean) with auto-refresh enabled. This method will link the given ViewPager and this TabLayout together so that changes in one are automatically reflected in the other.
The tabs displayed in this layout will be populated from the ViewPager adapter’s page titles. If autoRefresh is true , any changes in the PagerAdapter will trigger this layout to re-populate itself from the adapter’s titles.
Membuat tampilan geser dengan tab menggunakan ViewPager
Untuk memasukkan tampilan turunan yang mewakili setiap halaman, Anda harus menarik tata letak ini ke PagerAdapter . FragmentPagerAdapter – Gunakan adaptor ini saat melakukan navigasi antara layar setara yang tetap dalam jumlah kecil.
– Gunakan adaptor ini saat melakukan navigasi antara layar setara yang tetap dalam jumlah kecil. Contohnya, berikut adalah cara menggunakan FragmentStatePagerAdapter untuk menggeser kumpulan objek Fragment :
class DemoObjectFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? Jika digunakan bersama dengan ViewPager , TabLayout dapat memberikan antarmuka yang umum untuk melakukan navigasi antarhalaman dalam tampilan geser.
Setiap tab dalam TabLayout secara otomatis diisi dengan judul halaman dari PagerAdapter : Catatan: Jika Anda memiliki jumlah halaman yang besar atau mungkin tidak terbatas, tetapkan atribut android:tabMode pada TabLayout ke “dapat di-scroll”.
TabLayout Tutorial With Example In Android Studio
In Android TabLayout is a new element introduced in Design Support library. TabLayout is basically view class required to be added into our layout(xml) for creating Sliding Tabs. We use different methods of TabLayout to create, add and manage the tabs. Special Note: TabLayout is used to display tabs on the screen.
Below we firstly create a new tab and then add it in the TabLayout and set the true value for setSelected parameter that makes it selectable. Below we firstly create a new tab and then add it in the TabLayout at a specific position.
This method returns an int type value for the position of the selected tab. 8. getTabCount(): This method is used to get the number of tabs currently registered with the action bar. This method returns an int type value for the number of total tabs. Below we get the total number of tabs currently registered with the action bar. 10. getTabGravity(): This method is used to get the current gravity used for laying out tabs. They are best used for browsing contexts in touch interfaces when users don’t need to directly compare the tab labels.
14. getTabTextColors(): This method is used to get the text colors for the different states (normal, selected) of the tabs. Below we firstly create and add a tab and then remove it from the TabLayout. 18. removeTabAt(int position): This method is used to remove a tab from the layout. In this method we pass the position of the tab that we want to remove from the layout. Now let’s we discuss some common attributes of a TabLayout that helps us to configure it in our layout (xml). 4. support.design:tabIndicatorColor: This attribute is used to set the Color of the indicator used to show the currently selected tab.
5. support.design:tabIndicatorHeight: This attribute is used to set the height of the indicator used to show the currently selected tab. 8. support.design:tabMode: This attribute is used to set the behavior mode for the Tabs in this layout. android.support.design:tabPaddingBottom: Set padding along the bottom edge of the tabs. android.support.design:tabPaddingStart: Set padding along the start edge of the tabs. 10. support.design:tabSelectedTextColor: This attribute is used to set the text color to be applied to the currently selected tab. 11. support.design:tabTextColor: This method is used to set the default text color to be applied to tabs. . We can also set this programmatically using setTabTextColors(int normalColor, int selectedColor) method.
After that we implement setOnTabSelectedListener event and replace the FrameLayout with the fragment’s according to selected tab. Step 2: Open build.gradle and add Design support library dependency.
apply plugin: ‘com.android.application’ android { compileSdkVersion 23 buildToolsVersion “23.0.2” defaultConfig { applicationId “com.abhiandroid.tablayoutexample” 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.1.0’ compile ‘com.android.support:design:23.1.0’ // design support library } Step 3: Open res -> layout ->activity_main.xml (or) main.xml and add following code: In this step we add the code for displaying TabLayout and ViewPager in our xml file. In this step we open MainActivity and add the code for initiate the FrameLayout and TabLayout.
Finally we implement setOnTabSelectedListener event and replace the FrameLayout with the fragment’s according to selected tab. package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FirstFragment extends Fragment { public FirstFragment() { // 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_first, container, false); } }
package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SecondFragment extends Fragment { public SecondFragment() { // 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_second, container, false); } } package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ThirdFragment extends Fragment { public ThirdFragment() { // 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_third, container, false); } } Below is the example of TabLayout in which we display sliding tabs with the help of ViewPager. Step 2: Open build.gradle and add Design support library dependency.
apply plugin: ‘com.android.application’ android { compileSdkVersion 23 buildToolsVersion “23.0.2” defaultConfig { applicationId “com.abhiandroid.tablayoutexample” 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.1.0’ compile ‘com.android.support:design:23.1.0’ // design support library } Step 3: Open res -> layout ->activity_main.xml (or) main.xml and add following code:
In this step we open MainActivity and add the code for initiate the ViewPager and TabLayout. package com.abhiandroid.tablayoutexample; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; public class PagerAdapter extends FragmentStatePagerAdapter { int mNumOfTabs; public PagerAdapter(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: FirstFragment tab1 = new FirstFragment(); return tab1; case 1: SecondFragment tab2 = new SecondFragment(); return tab2; case 2: ThirdFragment tab3 = new ThirdFragment(); return tab3; default: return null; } } @Override public int getCount() { return mNumOfTabs; } }
package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FirstFragment extends Fragment { public FirstFragment() { // 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_first, container, false); } } package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class SecondFragment extends Fragment { public SecondFragment() { // 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_second, container, false); } }
package com.abhiandroid.tablayoutexample; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ThirdFragment extends Fragment { public ThirdFragment() { // 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_third, container, false); } }
Make Text Tab Open By Default In Android Studio
This means I then have to keyboard shortcut CTRL + SHIFT + -> every time to edit the layout in “Text” mode.
Android Tab Layout using Fragments and ViewPager | Android Studio | Java
Android Tab Layout using Fragments and ViewPager | Android Studio | Java Android Tab Layout using Fragments and ViewPager | Android Studio | Java
In this tutorial, we are going to create a simple tab layout using fragments and viewpager. TabLayout is released by Android after the deprecation of ActionBar.TabListener (API level 21). TabLayout is introduced in the design support library to implement tabs. Step 1: Design the main XML layout
Step 2: Create an adapter class import com.codewithgolap.tablayout.Fragments.SettingsFragment; public class MyAdapter extends FragmentPagerAdapter { private Context myContext;
int totalTabs; public MyAdapter(Context context, FragmentManager fm, int totalTabs) { public Fragment getItem(int position) {
// this counts total number of tabs public int getCount() {
Step 3: Add the functionality import com.google.android.material.tabs.TabLayout; public class SimpleTabLayout extends AppCompatActivity { TabLayout tabLayout; protected void onCreate(Bundle savedInstanceState) { public void onTabSelected(TabLayout.Tab tab) {
public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } Android App Developer
Creating an Android Tabbed Interface using the TabLayout Component
This chapter will demonstrate how to use another of the design library components, the TabLayout, which can be combined with the ViewPager class to create a tab based interface within an Android activity. Although not part of the design support library, the ViewPager is a useful companion class when used in conjunction with the TabLayout component to implement a tabbed user interface. The second method, getItem(), is passed a page number and must return the corresponding fragment object ready to be presented to the user. The remainder of this chapter will work through the creation of an example project that demonstrates the use of the TabLayout component together with a ViewPager and four fragments.
Create a new project in Android Studio, entering TabLayoutDemo into the Application name field and ebookfrenzy.com as the Company Domain setting before clicking on the Next button. Once the project has been created, load the content_tab_layout_demo.xml file into the Designer tool, select and then delete the “Hello World” TextView object. From the Palette, locate the Large Text widget and drag and drop it so that it is positioned into the center of the layout. Edit the text on the object so that it reads “Tab 1 Fragment” at which point the layout should match that of Figure 31-4:
Right-click on the fragment_tab1.xml file in the Project tool window and select the Copy option from the resulting menu. In the Copy Class dialog, enter Tab2Fragment into the New name: field and click on OK. Edit the new Tab2Fragment.java file and change the onCreateView() method to inflate the fragment_tab2 layout file: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_tab2, container, false); } Perform the above duplication steps twice more to create the fragment layout and class files for the remaining two fragments. With the fragment creation process now complete the next step is to add the TabLayout and ViewPager to the main activity layout file. In the new class dialog, enter TabPagerAdapter into the Name: field and click OK. Edit the TabPagerAdapter.java file so that it reads as follows:
A switch statement is used to identify the page number being requested and to return a corresponding fragment instance. Finally, the getCount() method simply returns the count value passed through when the object instance was created. Note that the code to create the TabPagerAdapter instance passes through the number of tabs that have been assigned to the TabLayout component. Note that the code to create the TabPagerAdapter instance passes through the number of tabs that have been assigned to the TabLayout component.
Compile and run the app on a device or emulator and make sure that selecting a tab causes the corresponding fragment to appear in the content area of the screen: A greater number of tabs or longer titles can quickly become a problem when using fixed mode as illustrated by Figure 31-7: In this mode the titles appear in full length, single line format allowing the user to swipe to scroll horizontally through the available items as demonstrated in Figure 31-8: This is controlled via the app:tabGravity property, the results of which are more noticeable on wider displays such as tablets in landscape orientation.
When set to “fill”, for example, the items will be distributed evenly across the width of the TabLayout as shown in Figure 31-9: Before proceeding to the final step in this chapter, revert the tabMode and tabGravity properties in the activity_tab_layout_demo.xml file to “fixed” and “fill” respectively.
Be First to Comment