37 | * To use the component, simply add it to your view hierarchy. Then in your 38 | * {@link android.app.Activity} or {@link android.support.v4.app.Fragment} call 39 | * {@link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for. 40 | *
41 | * The colors can be customized in two ways. The first and simplest is to provide an array of colors 42 | * via {@link #setSelectedIndicatorColors(int...)}. The 43 | * alternative is via the {@link TabColorizer} interface which provides you complete control over 44 | * which color is used for any individual position. 45 | *
46 | * The views used as tabs can be customized by calling {@link #setCustomTabView(int, int)},
47 | * providing the layout ID of your custom layout.
48 | */
49 | public class SlidingTabLayout extends HorizontalScrollView {
50 | /**
51 | * Allows complete control over the colors drawn in the tab layout. Set with
52 | * {@link #setCustomTabColorizer(TabColorizer)}.
53 | */
54 | public interface TabColorizer {
55 |
56 | /**
57 | * @return return the color of the indicator used when {@code position} is selected.
58 | */
59 | int getIndicatorColor(int position);
60 |
61 | }
62 |
63 | private static final int TITLE_OFFSET_DIPS = 24;
64 | private static final int TAB_VIEW_PADDING_DIPS = 16;
65 | private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
66 |
67 | private int mTitleOffset;
68 |
69 | private int mTabViewLayoutId;
70 | private int mTabViewTextViewId;
71 | private boolean mDistributeEvenly;
72 |
73 | private ViewPager mViewPager;
74 | private SparseArray
104 | * If you only require simple custmisation then you can use
105 | * {@link #setSelectedIndicatorColors(int...)} to achieve
106 | * similar effects.
107 | */
108 | public void setCustomTabColorizer(TabColorizer tabColorizer) {
109 | mTabStrip.setCustomTabColorizer(tabColorizer);
110 | }
111 |
112 | public void setDistributeEvenly(boolean distributeEvenly) {
113 | mDistributeEvenly = distributeEvenly;
114 | }
115 |
116 | /**
117 | * Sets the colors to be used for indicating the selected tab. These colors are treated as a
118 | * circular array. Providing one color will mean that all tabs are indicated with the same color.
119 | */
120 | public void setSelectedIndicatorColors(int... colors) {
121 | mTabStrip.setSelectedIndicatorColors(colors);
122 | }
123 |
124 | /**
125 | * Set the {@link ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are
126 | * required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so
127 | * that the layout can update it's scroll position correctly.
128 | *
129 | * @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
130 | */
131 | public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
132 | mViewPagerPageChangeListener = listener;
133 | }
134 |
135 | /**
136 | * Set the custom layout to be inflated for the tab views.
137 | *
138 | * @param layoutResId Layout id to be inflated
139 | * @param textViewId id of the {@link TextView} in the inflated view
140 | */
141 | public void setCustomTabView(int layoutResId, int textViewId) {
142 | mTabViewLayoutId = layoutResId;
143 | mTabViewTextViewId = textViewId;
144 | }
145 |
146 | /**
147 | * Sets the associated view pager. Note that the assumption here is that the pager content
148 | * (number of tabs and tab titles) does not change after this call has been made.
149 | */
150 | public void setViewPager(ViewPager viewPager) {
151 | mTabStrip.removeAllViews();
152 |
153 | mViewPager = viewPager;
154 | if (viewPager != null) {
155 | viewPager.setOnPageChangeListener(new InternalViewPagerListener());
156 | populateTabStrip();
157 | }
158 | }
159 |
160 | /**
161 | * Create a default view to be used for tabs. This is called if a custom tab view is not set via
162 | * {@link #setCustomTabView(int, int)}.
163 | */
164 | protected TextView createDefaultTabView(Context context) {
165 | TextView textView = new TextView(context);
166 | textView.setGravity(Gravity.CENTER);
167 | textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
168 | textView.setTypeface(Typeface.DEFAULT_BOLD);
169 | textView.setLayoutParams(new LinearLayout.LayoutParams(
170 | ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
171 |
172 | TypedValue outValue = new TypedValue();
173 | getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
174 | outValue, true);
175 | textView.setBackgroundResource(outValue.resourceId);
176 | textView.setAllCaps(true);
177 |
178 | int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
179 | textView.setPadding(padding, padding, padding, padding);
180 |
181 | return textView;
182 | }
183 |
184 | private void populateTabStrip() {
185 | final PagerAdapter adapter = mViewPager.getAdapter();
186 | final OnClickListener tabClickListener = new TabClickListener();
187 |
188 | for (int i = 0; i < adapter.getCount(); i++) {
189 | View tabView = null;
190 | TextView tabTitleView = null;
191 |
192 | if (mTabViewLayoutId != 0) {
193 | // If there is a custom tab view layout id set, try and inflate it
194 | tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
195 | false);
196 | tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
197 | }
198 |
199 | if (tabView == null) {
200 | tabView = createDefaultTabView(getContext());
201 | }
202 |
203 | if (tabTitleView == null && TextView.class.isInstance(tabView)) {
204 | tabTitleView = (TextView) tabView;
205 | }
206 |
207 | if (mDistributeEvenly) {
208 | LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
209 | lp.width = 0;
210 | lp.weight = 1;
211 | }
212 |
213 | tabTitleView.setText(adapter.getPageTitle(i));
214 | tabView.setOnClickListener(tabClickListener);
215 | String desc = mContentDescriptions.get(i, null);
216 | if (desc != null) {
217 | tabView.setContentDescription(desc);
218 | }
219 |
220 | mTabStrip.addView(tabView);
221 | if (i == mViewPager.getCurrentItem()) {
222 | tabView.setSelected(true);
223 | }
224 | }
225 | }
226 |
227 | public void setContentDescription(int i, String desc) {
228 | mContentDescriptions.put(i, desc);
229 | }
230 |
231 | @Override
232 | protected void onAttachedToWindow() {
233 | super.onAttachedToWindow();
234 |
235 | if (mViewPager != null) {
236 | scrollToTab(mViewPager.getCurrentItem(), 0);
237 | }
238 | }
239 |
240 | private void scrollToTab(int tabIndex, int positionOffset) {
241 | final int tabStripChildCount = mTabStrip.getChildCount();
242 | if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
243 | return;
244 | }
245 |
246 | View selectedChild = mTabStrip.getChildAt(tabIndex);
247 | if (selectedChild != null) {
248 | int targetScrollX = selectedChild.getLeft() + positionOffset;
249 |
250 | if (tabIndex > 0 || positionOffset > 0) {
251 | // If we're not at the first child and are mid-scroll, make sure we obey the offset
252 | targetScrollX -= mTitleOffset;
253 | }
254 |
255 | scrollTo(targetScrollX, 0);
256 | }
257 | }
258 |
259 | private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
260 | private int mScrollState;
261 |
262 | @Override
263 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
264 | int tabStripChildCount = mTabStrip.getChildCount();
265 | if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
266 | return;
267 | }
268 |
269 | mTabStrip.onViewPagerPageChanged(position, positionOffset);
270 |
271 | View selectedTitle = mTabStrip.getChildAt(position);
272 | int extraOffset = (selectedTitle != null)
273 | ? (int) (positionOffset * selectedTitle.getWidth())
274 | : 0;
275 | scrollToTab(position, extraOffset);
276 |
277 | if (mViewPagerPageChangeListener != null) {
278 | mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
279 | positionOffsetPixels);
280 | }
281 | }
282 |
283 | @Override
284 | public void onPageScrollStateChanged(int state) {
285 | mScrollState = state;
286 |
287 | if (mViewPagerPageChangeListener != null) {
288 | mViewPagerPageChangeListener.onPageScrollStateChanged(state);
289 | }
290 | }
291 |
292 | @Override
293 | public void onPageSelected(int position) {
294 | if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
295 | mTabStrip.onViewPagerPageChanged(position, 0f);
296 | scrollToTab(position, 0);
297 | }
298 | for (int i = 0; i < mTabStrip.getChildCount(); i++) {
299 | mTabStrip.getChildAt(i).setSelected(position == i);
300 | }
301 | if (mViewPagerPageChangeListener != null) {
302 | mViewPagerPageChangeListener.onPageSelected(position);
303 | }
304 | }
305 |
306 | }
307 |
308 | private class TabClickListener implements OnClickListener {
309 | @Override
310 | public void onClick(View v) {
311 | for (int i = 0; i < mTabStrip.getChildCount(); i++) {
312 | if (v == mTabStrip.getChildAt(i)) {
313 | mViewPager.setCurrentItem(i);
314 | return;
315 | }
316 | }
317 | }
318 | }
319 |
320 | }
--------------------------------------------------------------------------------
/sample/src/main/java/sundeepk/github/com/sample/SlidingTabStrip.java:
--------------------------------------------------------------------------------
1 | package sundeepk.github.com.sample;
2 |
3 | /*
4 | * Copyright 2014 Google Inc. All rights reserved.
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | import android.content.Context;
20 | import android.graphics.Canvas;
21 | import android.graphics.Color;
22 | import android.graphics.Paint;
23 | import android.util.AttributeSet;
24 | import android.util.TypedValue;
25 | import android.view.View;
26 | import android.widget.LinearLayout;
27 |
28 | class SlidingTabStrip extends LinearLayout {
29 |
30 | private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
31 | private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
32 | private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 3;
33 | private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;
34 |
35 | private final int mBottomBorderThickness;
36 | private final Paint mBottomBorderPaint;
37 |
38 | private final int mSelectedIndicatorThickness;
39 | private final Paint mSelectedIndicatorPaint;
40 |
41 | private int mSelectedPosition;
42 | private float mSelectionOffset;
43 |
44 | private SlidingTabLayout.TabColorizer mCustomTabColorizer;
45 | private final SimpleTabColorizer mDefaultTabColorizer;
46 |
47 | SlidingTabStrip(Context context) {
48 | this(context, null);
49 | }
50 |
51 | SlidingTabStrip(Context context, AttributeSet attrs) {
52 | super(context, attrs);
53 | setWillNotDraw(false);
54 |
55 | final float density = getResources().getDisplayMetrics().density;
56 |
57 | TypedValue outValue = new TypedValue();
58 | context.getTheme().resolveAttribute(android.R.attr.colorForeground, outValue, true);
59 | final int themeForegroundColor = outValue.data;
60 |
61 | int defaultBottomBorderColor = setColorAlpha(themeForegroundColor,
62 | DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
63 |
64 | mDefaultTabColorizer = new SimpleTabColorizer();
65 | mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
66 |
67 | mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
68 | mBottomBorderPaint = new Paint();
69 | mBottomBorderPaint.setColor(defaultBottomBorderColor);
70 |
71 | mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
72 | mSelectedIndicatorPaint = new Paint();
73 | }
74 |
75 | void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
76 | mCustomTabColorizer = customTabColorizer;
77 | invalidate();
78 | }
79 |
80 | void setSelectedIndicatorColors(int... colors) {
81 | // Make sure that the custom colorizer is removed
82 | mCustomTabColorizer = null;
83 | mDefaultTabColorizer.setIndicatorColors(colors);
84 | invalidate();
85 | }
86 |
87 | void onViewPagerPageChanged(int position, float positionOffset) {
88 | mSelectedPosition = position;
89 | mSelectionOffset = positionOffset;
90 | invalidate();
91 | }
92 |
93 | @Override
94 | protected void onDraw(Canvas canvas) {
95 | final int height = getHeight();
96 | final int childCount = getChildCount();
97 | final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
98 | ? mCustomTabColorizer
99 | : mDefaultTabColorizer;
100 |
101 | // Thick colored underline below the current selection
102 | if (childCount > 0) {
103 | View selectedTitle = getChildAt(mSelectedPosition);
104 | int left = selectedTitle.getLeft();
105 | int right = selectedTitle.getRight();
106 | int color = tabColorizer.getIndicatorColor(mSelectedPosition);
107 |
108 | if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
109 | int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
110 | if (color != nextColor) {
111 | color = blendColors(nextColor, color, mSelectionOffset);
112 | }
113 |
114 | // Draw the selection partway between the tabs
115 | View nextTitle = getChildAt(mSelectedPosition + 1);
116 | left = (int) (mSelectionOffset * nextTitle.getLeft() +
117 | (1.0f - mSelectionOffset) * left);
118 | right = (int) (mSelectionOffset * nextTitle.getRight() +
119 | (1.0f - mSelectionOffset) * right);
120 | }
121 |
122 | mSelectedIndicatorPaint.setColor(color);
123 |
124 | canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
125 | height, mSelectedIndicatorPaint);
126 | }
127 |
128 | // Thin underline along the entire bottom edge
129 | canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
130 | }
131 |
132 | /**
133 | * Set the alpha value of the {@code color} to be the given {@code alpha} value.
134 | */
135 | private static int setColorAlpha(int color, byte alpha) {
136 | return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
137 | }
138 |
139 | /**
140 | * Blend {@code color1} and {@code color2} using the given ratio.
141 | *
142 | * @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
143 | * 0.0 will return {@code color2}.
144 | */
145 | private static int blendColors(int color1, int color2, float ratio) {
146 | final float inverseRation = 1f - ratio;
147 | float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
148 | float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
149 | float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
150 | return Color.rgb((int) r, (int) g, (int) b);
151 | }
152 |
153 | private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
154 | private int[] mIndicatorColors;
155 |
156 | @Override
157 | public final int getIndicatorColor(int position) {
158 | return mIndicatorColors[position % mIndicatorColors.length];
159 | }
160 |
161 | void setIndicatorColors(int... colors) {
162 | mIndicatorColors = colors;
163 | }
164 | }
165 | }
--------------------------------------------------------------------------------
/sample/src/main/java/sundeepk/github/com/sample/Tab2.java:
--------------------------------------------------------------------------------
1 | package sundeepk.github.com.sample;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.Nullable;
5 | import android.support.v4.app.Fragment;
6 | import android.view.LayoutInflater;
7 | import android.view.View;
8 | import android.view.ViewGroup;
9 |
10 | public class Tab2 extends Fragment {
11 | @Override
12 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
13 | View v = inflater.inflate(R.layout.tab_2,container,false);
14 | return v;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/sample/src/main/java/sundeepk/github/com/sample/ViewPagerAdapter.java:
--------------------------------------------------------------------------------
1 | package sundeepk.github.com.sample;
2 |
3 | import android.support.v4.app.Fragment;
4 | import android.support.v4.app.FragmentManager;
5 | import android.support.v4.app.FragmentStatePagerAdapter;
6 |
7 | public class ViewPagerAdapter extends FragmentStatePagerAdapter {
8 |
9 | CharSequence titles[];
10 | int numbOfTabs;
11 |
12 | public ViewPagerAdapter(FragmentManager fm, CharSequence titles[], int mNumbOfTabs) {
13 | super(fm);
14 | this.titles = titles;
15 | this.numbOfTabs = mNumbOfTabs;
16 | }
17 |
18 | @Override
19 | public Fragment getItem(int position) {
20 | if (position == 0) {
21 | CompactCalendarTab compactCalendarTab = new CompactCalendarTab();
22 | return compactCalendarTab;
23 | } else {
24 | Tab2 tab2 = new Tab2();
25 | return tab2;
26 | }
27 | }
28 |
29 | @Override
30 | public CharSequence getPageTitle(int position) {
31 | return titles[position];
32 | }
33 |
34 | @Override
35 | public int getCount() {
36 | return numbOfTabs;
37 | }
38 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |