Make Scrollable Or Fixed Mode In Tablayout For Dynamic Number Of Tabs
I want tabMode scrollable with tabFilled with tabs(having single line title). As number of Tab and their title is dynamic in my app. How could I handle them when I set given pr
Solution 1:
I come up with a new and better solution..
List<String> titleTabs = getTitleOfTab();
for (String module : titleTabs) {
mTabLayout.addTab(mTabLayout.newTab().setText(module));
}
mTabLayout.post(newRunnable()
{
@Overridepublicvoidrun()
{
// don't forget to add Tab first before measuring..DisplayMetricsdisplayMetrics=newDisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
intwidthS= displayMetrics.widthPixels;
mTabLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
intwidthT= mTabLayout.getMeasuredWidth();
if (widthS > widthT) {
mTabLayout.setTabMode(TabLayout.MODE_FIXED);
mTabLayout.setLayoutParams(newLinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
}
}
});
where tablayout in xml must have tabGravity Fill and tabMode to Scrollable
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:minHeight="?attr/actionBarSize"
app:tabGravity="fill"
app:tabIndicatorHeight="4dp"
app:tabMode="scrollable"/>
Solution 2:
try this one
publicclassSlidingTabLayoutextendsHorizontalScrollView {
/**
* Allows complete control over the colors drawn in the tab layout. Set with
* {@link #setCustomTabColorizer(TabColorizer)}.
*/publicinterfaceTabColorizer {
/**
* @return return the color of the indicator used when {@code position} is selected.
*/intgetIndicatorColor(int position);
}
privatestaticfinalintTITLE_OFFSET_DIPS=24;
privatestaticfinalintTAB_VIEW_PADDING_DIPS=16;
privatestaticfinalintTAB_VIEW_TEXT_SIZE_SP=12;
privateint mTitleOffset;
privateint mTabViewLayoutId;
privateint mTabViewTextViewId;
privateboolean mDistributeEvenly;
private ViewPager mViewPager;
private SparseArray<String> mContentDescriptions = newSparseArray<String>();
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
privatefinal SlidingTabStrip mTabStrip;
publicSlidingTabLayout(Context context) {
this(context, null);
}
publicSlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
publicSlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = newSlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {@link TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {@link #setSelectedIndicatorColors(int...)} to achieve
* similar effects.
*/publicvoidsetCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
publicvoidsetDistributeEvenly(boolean distributeEvenly) {
mDistributeEvenly = distributeEvenly;
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/publicvoidsetSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
/**
* Set the {@link ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are
* required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
*/publicvoidsetOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* @param layoutResId Layout id to be inflated
* @param textViewId id of the {@link TextView} in the inflated view
*/publicvoidsetCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/publicvoidsetViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(newInternalViewPagerListener());
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {@link #setCustomTabView(int, int)}.
*/@SuppressLint("NewApi")protected TextView createDefaultTabView(Context context) {
TextViewtextView=newTextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(newLinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValueoutValue=newTypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
textView.setAllCaps(true);
intpadding= (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
/*private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
if (mDistributeEvenly) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
lp.width = 0;
lp.weight = 1;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
String desc = mContentDescriptions.get(i, null);
if (desc != null) {
tabView.setContentDescription(desc);
}
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
}
}*/@SuppressWarnings("deprecation")privatevoidpopulateTabStrip() {
finalPagerAdapteradapter= mViewPager.getAdapter();
final View.OnClickListenertabClickListener=newTabClickListener();
for (inti=0; i < adapter.getCount(); i++) {
ViewtabView=null;
TextViewtabTitleView=null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
if (mDistributeEvenly) {
LinearLayout.LayoutParamslp= (LinearLayout.LayoutParams) tabView.getLayoutParams();
lp.width = 0;
lp.weight = 1;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
Stringdesc= mContentDescriptions.get(i, null);
if (desc != null) {
tabView.setContentDescription(desc);
}
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
tabTitleView.setTextColor(getResources().getColorStateList(R.drawable.selector));
tabTitleView.setTextSize(14);
}
}
publicvoidsetContentDescription(int i, String desc) {
mContentDescriptions.put(i, desc);
}
@OverrideprotectedvoidonAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
privatevoidscrollToTab(int tabIndex, int positionOffset) {
finalinttabStripChildCount= mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
ViewselectedChild= mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
inttargetScrollX= selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
privateclassInternalViewPagerListenerimplementsViewPager.OnPageChangeListener {
privateint mScrollState;
@OverridepublicvoidonPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
inttabStripChildCount= mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
ViewselectedTitle= mTabStrip.getChildAt(position);
intextraOffset= (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
@OverridepublicvoidonPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
@OverridepublicvoidonPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (inti=0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
privateclassTabClickListenerimplementsView.OnClickListener {
@OverridepublicvoidonClick(View v) {
for (inti=0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
SlidingTabStrip.java
classSlidingTabStripextendsLinearLayout {
privatestaticfinalintDEFAULT_BOTTOM_BORDER_THICKNESS_DIPS=0;
privatestaticfinalbyteDEFAULT_BOTTOM_BORDER_COLOR_ALPHA=0x26;
privatestaticfinalintSELECTED_INDICATOR_THICKNESS_DIPS=3;
privatestaticfinalintDEFAULT_SELECTED_INDICATOR_COLOR=0xFF33B5E5;
privatefinalint mBottomBorderThickness;
privatefinal Paint mBottomBorderPaint;
privatefinalint mSelectedIndicatorThickness;
privatefinal Paint mSelectedIndicatorPaint;
privatefinalint mDefaultBottomBorderColor;
privateint mSelectedPosition;
privatefloat mSelectionOffset;
private SlidingTabLayout.TabColorizer mCustomTabColorizer;
privatefinal SimpleTabColorizer mDefaultTabColorizer;
SlidingTabStrip(Context context) {
this(context, null);
}
SlidingTabStrip(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
finalfloatdensity= getResources().getDisplayMetrics().density;
TypedValueoutValue=newTypedValue();
context.getTheme().resolveAttribute(R.attr.colorForeground, outValue, true);
finalintthemeForegroundColor= outValue.data;
mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor, DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = newSimpleTabColorizer();
mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = newPaint();
mBottomBorderPaint.setColor(mDefaultBottomBorderColor);
mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = newPaint();
}
voidsetCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
mCustomTabColorizer = customTabColorizer;
invalidate();
}
voidsetSelectedIndicatorColors(int... colors) {
// Make sure that the custom colorizer is removed
mCustomTabColorizer = null;
mDefaultTabColorizer.setIndicatorColors(colors);
invalidate();
}
voidonViewPagerPageChanged(int position, float positionOffset) {
mSelectedPosition = position;
mSelectionOffset = positionOffset;
invalidate();
}
@OverrideprotectedvoidonDraw(Canvas canvas) {
finalintheight= getHeight();
finalintchildCount= getChildCount();
final SlidingTabLayout.TabColorizertabColorizer= mCustomTabColorizer != null
? mCustomTabColorizer
: mDefaultTabColorizer;
// Thick colored underline below the current selectionif (childCount > 0) {
ViewselectedTitle= getChildAt(mSelectedPosition);
intleft= selectedTitle.getLeft();
intright= selectedTitle.getRight();
intcolor= tabColorizer.getIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
intnextColor= tabColorizer.getIndicatorColor(mSelectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, mSelectionOffset);
}
// Draw the selection partway between the tabsViewnextTitle= getChildAt(mSelectedPosition + 1);
left = (int) (mSelectionOffset * nextTitle.getLeft() +
(1.0f - mSelectionOffset) * left);
right = (int) (mSelectionOffset * nextTitle.getRight() +
(1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
height, mSelectedIndicatorPaint);
}
// Thin underline along the entire bottom edge
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
}
/**
* Set the alpha value of the {@code color} to be the given {@code alpha} value.
*/privatestaticintsetColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Blend {@code color1} and {@code color2} using the given ratio.
*
* @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
* 0.0 will return {@code color2}.
*/privatestaticintblendColors(int color1, int color2, float ratio) {
finalfloatinverseRation=1f - ratio;
floatr= (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
floatg= (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
floatb= (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
}
privatestaticclassSimpleTabColorizerimplementsSlidingTabLayout.TabColorizer {
privateint[] mIndicatorColors;
@OverridepublicfinalintgetIndicatorColor(int position) {
return mIndicatorColors[position % mIndicatorColors.length];
}
voidsetIndicatorColors(int... colors) {
mIndicatorColors = colors;
}
}
}
USE in
xml
like this
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><com.helper.SlidingTabLayoutandroid:id="@+id/tabs"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@color/colorPrimary"></com.helper.SlidingTabLayout><FrameLayoutandroid:id="@+id/content_frame"android:layout_width="fill_parent"android:layout_height="fill_parent"><android.support.v4.view.ViewPagerandroid:id="@+id/pager"android:layout_width="fill_parent"android:layout_height="fill_parent"></android.support.v4.view.ViewPager></FrameLayout></LinearLayout>
In java class Where you are using this add below code
ViewPagerpager= (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(YourPagerAdapter);
SlidingTabLayouttabs= (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setSelectedIndicatorColors(android.R.color.white,android.R.color.white,android.R.color.white);
tabs.setCustomTabColorizer(newSlidingTabLayout.TabColorizer() {
@OverridepublicintgetIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
Post a Comment for "Make Scrollable Or Fixed Mode In Tablayout For Dynamic Number Of Tabs"