使用SlIDingTabLayout需要准备2个类,分别是 SlIDingTabLayout,与SlIDingTabStrip,,放进项目中时只用修改下包名即可。
效果制作的不是很好。
这篇文章,也是在网上搜了很多资源参考,对 SlIDingTabLayout.java和SlIDingTabStrip.java进行了修改。大家可以更改他的格式字体大小、选中状态,分割线调整等等。先上传这两个文件,改动支出都做了注释。
SlIDingTabLayout.java
/* * copyright (C) 2013 The AndroID Open Source Project * * licensed under the Apache license,Version 2.0 (the "license"); * you may not use this file except in compliance with the license. * You may obtain a copy of the license at * * http://www.apache.org/licenses/liCENSE-2.0 * * Unless required by applicable law or agreed to in writing,software * distributed under the license is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implIEd. * See the license for the specific language governing permissions and * limitations under the license. */package com.example.my.slIDingtablayout;import androID.content.Context;import androID.content.res.TypedArray;import androID.graphics.color;import androID.graphics.Typeface;import androID.os.Build;import androID.support.v4.vIEw.PagerAdapter;import androID.support.v4.vIEw.VIEwPager;import androID.util.AttributeSet;import androID.util.TypedValue;import androID.vIEw.Gravity;import androID.vIEw.LayoutInflater;import androID.vIEw.VIEw;import androID.Widget.horizontalscrollview;import androID.Widget.linearLayout;import androID.Widget.TextVIEw;/** * To be used with VIEwPager to provIDe a tab indicator component which give constant Feedback as to * the user's scroll progress. * <p> * To use the component,simply add it to your vIEw hIErarchy. Then in your * {@link androID.app.Activity} or {@link androID.support.v4.app.Fragment} call * {@link #setVIEwPager(VIEwPager)} provIDing it the VIEwPager this layout is being used for. * <p> * The colors can be customized in two ways. The first and simplest is to provIDe an array of colors * via {@link #setSelectedindicatorcolors(int...)} and {@link #setdivIDercolors(int...)}. The * alternative is via the {@link Tabcolorizer} interface which provIDes you complete control over * which color is used for any indivIDual position. * <p> * The vIEws used as tabs can be customized by calling {@link #setCustomTabVIEw(int,int)},* provIDing the layout ID of your custom layout. */public class SlIDingTabLayout extends horizontalscrollview { /** * Allows complete control over the colors drawn in the tab layout. Set with * {@link #setCustomTabcolorizer(Tabcolorizer)}. */ public interface Tabcolorizer { /** * @return return the color of the indicator used when {@code position} is selected. */ int getIndicatorcolor(int position); /** * @return return the color of the divIDer drawn to the right of {@code position}. */ int getdivIDercolor(int position); } private static final int Title_OFFSET_DIPS = 24; private static final int TAB_VIEW_padding_DIPS = 16; //内边距 private static int TAB_VIEW_TEXT_SIZE_SP = 16; //字体大小 private int mTitleOffset; private int mTabVIEwLayoutID; private int mTabVIEwTextVIEwID; // 定义两种需要添加的选项卡颜色 private int mDefaultTextcolor; private int mSelectedTextcolor; private VIEwPager mVIEwPager; private VIEwPager.OnPagechangelistener mVIEwPagerPagechangelistener; private final SlIDingTabStrip mTabStrip; public SlIDingTabLayout(Context context) { this(context,null); } public SlIDingTabLayout(Context context,AttributeSet attrs) { this(context,attrs,0); } public SlIDingTabLayout(Context context,AttributeSet attrs,int defStyle) { super(context,defStyle); // 获取选项卡颜色,如果未定义的话,则使用主题默认的颜色 TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.SlIDingTabLayout); int defaultTextcolor = a.getcolor( R.styleable.SlIDingTabLayout_androID_textcolorPrimary,0); mDefaultTextcolor = a.getcolor( R.styleable.SlIDingTabLayout_textcolorTabDefault,defaultTextcolor); mSelectedTextcolor = a.getcolor( R.styleable.SlIDingTabLayout_textcolorTabSelected,defaultTextcolor); a.recycle(); // 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 = new SlIDingTabStrip(context); addVIEw(mTabStrip,LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); } // 在每次选项改变时更新选项卡文本颜色的新方法 private voID updateSelectedTitle(int position) { final PagerAdapter adapter = mVIEwPager.getAdapter(); for (int i = 0; i < adapter.getCount(); i++) { final VIEw tabVIEw = mTabStrip.getChildAt(i); if (TextVIEw.class.isinstance(tabVIEw)) { TextVIEw TitleVIEw = (TextVIEw)tabVIEw; boolean isSelected = i == position; TitleVIEw.setTextcolor(isSelected ? mSelectedTextcolor : mDefaultTextcolor); } } } /** * Set the custom {@link Tabcolorizer} to be used. * <p> * If you only require simple custmisation then you can use * {@link #setSelectedindicatorcolors(int...)} and {@link #setdivIDercolors(int...)} to achIEve * similar effects. */ public voID setCustomTabcolorizer(Tabcolorizer tabcolorizer) { mTabStrip.setCustomTabcolorizer(tabcolorizer); } /** * 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. */ public voID setSelectedindicatorcolors(int... colors) { mTabStrip.setSelectedindicatorcolors(colors); } /** * Sets the colors to be used for tab divIDers. These colors are treated as a circular array. * ProvIDing one color will mean that all tabs are indicated with the same color. */ public voID setdivIDercolors(int... colors) { mTabStrip.setdivIDercolors(colors); } //...设置字体大小 public voID setTitleSize(int size) { this.TAB_VIEW_TEXT_SIZE_SP = size; } /** * 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) */ public voID setonPagechangelistener(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 */ public voID setCustomTabVIEw(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. */ public voID setVIEwPager(VIEwPager vIEwPager) { mTabStrip.removeAllVIEws(); mVIEwPager = vIEwPager; if (vIEwPager != null) { vIEwPager.setonPagechangelistener(new InternalVIEwPagerListener()); 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)}. */ protected TextVIEw createDefaultTabVIEw(Context context) { TextVIEw textVIEw = new TextVIEw(context); textVIEw.setGravity(Gravity.CENTER); textVIEw.setTextSize(TypedValue.COMPLEX_UNIT_SP,TAB_VIEW_TEXT_SIZE_SP); textVIEw.setTypeface(Typeface.DEFAulT_BolD); //...这会移除 Holo 的默认背景强调以及选项卡的粗体文本 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // If we're running on Honeycomb or newer,then we can use the theme's // selectableItemBackground to ensure that the VIEw has a pressed state TypedValue outValue = new TypedValue(); getContext().gettheme().resolveAttribute(androID.R.attr.selectableItemBackground,outValue,true); textVIEw.setBackgroundResource(outValue.resourceID); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // If we're running on ICS or newer,enable all-caps to match the Action bar tab style textVIEw.setAllCaps(true); } int padding = (int) (TAB_VIEW_padding_DIPS * getResources().getdisplayMetrics().density); textVIEw.setpadding(padding,padding,padding); return textVIEw; } private voID populateTabStrip() { final PagerAdapter adapter = mVIEwPager.getAdapter(); final 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; } tabTitleVIEw.setText(adapter.getPageTitle(i)); //... 设置头部均分 linearLayout.LayoutParams layoutParams = new linearLayout.LayoutParams(0,LayoutParams.WRAP_CONTENT,1.0f); tabVIEw.setLayoutParams(layoutParams); tabVIEw.setonClickListener(tabClickListener); mTabStrip.addVIEw(tabVIEw); } } @OverrIDe protected voID onAttachedToWindow() { super.onAttachedToWindow(); if (mVIEwPager != null) { scrollToTab(mVIEwPager.getCurrentItem(),0); } } private voID scrollToTab(int tabIndex,int positionOffset) { final int tabStripChildCount = mTabStrip.getChildCount(); if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) { return; } VIEw selectedChild = mTabStrip.getChildAt(tabIndex); if (selectedChild != null) { // 调用在每次选项改变时更新文本颜色的新方案 updateSelectedTitle(tabIndex); int targetScrollX = 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); } } private class InternalVIEwPagerListener implements VIEwPager.OnPagechangelistener { private int mScrollState; @OverrIDe public voID onPageScrolled(int position,float positionOffset,int positionOffsetPixels) { int tabStripChildCount = mTabStrip.getChildCount(); if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) { return; } mTabStrip.onVIEwPagerPageChanged(position,positionOffset); VIEw selectedTitle = mTabStrip.getChildAt(position); int extraOffset = (selectedTitle != null) ? (int) (positionOffset * selectedTitle.getWIDth()) : 0; scrollToTab(position,extraOffset); if (mVIEwPagerPagechangelistener != null) { mVIEwPagerPagechangelistener.onPageScrolled(position,positionOffset,positionOffsetPixels); } } @OverrIDe public voID onPageScrollStateChanged(int state) { mScrollState = state; if (mVIEwPagerPagechangelistener != null) { mVIEwPagerPagechangelistener.onPageScrollStateChanged(state); } } @OverrIDe public voID onPageSelected(int position) { if (mScrollState == VIEwPager.SCRolL_STATE_IDLE) { mTabStrip.onVIEwPagerPageChanged(position,0f); scrollToTab(position,0); } if (mVIEwPagerPagechangelistener != null) { mVIEwPagerPagechangelistener.onPageSelected(position); } } } private class TabClickListener implements OnClickListener { @OverrIDe public voID onClick(VIEw v) { for (int i = 0; i < mTabStrip.getChildCount(); i++) { if (v == mTabStrip.getChildAt(i)) { mVIEwPager.setCurrentItem(i); return; } } } }}
SlIDingTabStrip.java
/* * copyright (C) 2013 The AndroID Open Source Project * * licensed under the Apache license,either express or implIEd. * See the license for the specific language governing permissions and * limitations under the license. */package com.example.my.slIDingtablayout;import androID.R;import androID.content.Context;import androID.graphics.Canvas;import androID.graphics.color;import androID.graphics.Paint;import androID.util.AttributeSet;import androID.util.TypedValue;import androID.vIEw.VIEw;import androID.Widget.linearLayout;class SlIDingTabStrip extends linearLayout { private static final int DEFAulT_BottOM_border_THICKnesS_DIPS = 0; //去除阴影 private static final byte DEFAulT_BottOM_border_color_Alpha = 0x26; private static final int SELECTED_INDICATOR_THICKnesS_DIPS = 4; //设置滚动条的高度 private static final int DEFAulT_SELECTED_INDICATOR_color = 0xFF33B5E5; private static final int DEFAulT_divIDER_THICKnesS_DIPS = 1; private static final byte DEFAulT_divIDER_color_Alpha = 0x20; private static final float DEFAulT_divIDER_HEIGHT = 0.5f; private final int mBottomborderThickness; private final Paint mBottomborderPaint; private final int mSelectedindicatorThickness; private final Paint mSelectedindicatorPaint; private final int mDefaultBottombordercolor; private final Paint mdivIDerPaint; private final float mdivIDerHeight; private int mSelectedposition; private float mSelectionOffset; private SlIDingTabLayout.Tabcolorizer mCustomTabcolorizer; private final SimpleTabcolorizer mDefaultTabcolorizer; SlIDingTabStrip(Context context) { this(context,null); } SlIDingTabStrip(Context context,AttributeSet attrs) { super(context,attrs); setwillNotDraw(false); final float density = getResources().getdisplayMetrics().density; TypedValue outValue = new TypedValue(); context.gettheme().resolveAttribute(R.attr.colorForeground,true); final int themeForegroundcolor = outValue.data; mDefaultBottombordercolor = setcolorAlpha(themeForegroundcolor,DEFAulT_BottOM_border_color_Alpha); mDefaultTabcolorizer = new SimpleTabcolorizer(); mDefaultTabcolorizer.setIndicatorcolors(DEFAulT_SELECTED_INDICATOR_color); mDefaultTabcolorizer.setdivIDercolors(setcolorAlpha(themeForegroundcolor,DEFAulT_divIDER_color_Alpha)); mBottomborderThickness = (int) (DEFAulT_BottOM_border_THICKnesS_DIPS * density); mBottomborderPaint = new Paint(); mBottomborderPaint.setcolor(mDefaultBottombordercolor); mSelectedindicatorThickness = (int) (SELECTED_INDICATOR_THICKnesS_DIPS * density); mSelectedindicatorPaint = new Paint(); mdivIDerHeight = DEFAulT_divIDER_HEIGHT; mdivIDerPaint = new Paint(); mdivIDerPaint.setstrokeWIDth((int) (DEFAulT_divIDER_THICKnesS_DIPS * density)); } voID setCustomTabcolorizer(SlIDingTabLayout.Tabcolorizer customTabcolorizer) { mCustomTabcolorizer = customTabcolorizer; invalIDate(); } voID setSelectedindicatorcolors(int... colors) { // Make sure that the custom colorizer is removed mCustomTabcolorizer = null; mDefaultTabcolorizer.setIndicatorcolors(colors); invalIDate(); } voID setdivIDercolors(int... colors) { // Make sure that the custom colorizer is removed mCustomTabcolorizer = null; mDefaultTabcolorizer.setdivIDercolors(colors); invalIDate(); } voID onVIEwPagerPageChanged(int position,float positionOffset) { mSelectedposition = position; mSelectionOffset = positionOffset; invalIDate(); } @OverrIDe protected voID onDraw(Canvas canvas) { final int height = getHeight(); final int childCount = getChildCount(); final int divIDerHeightPx = (int) (Math.min(Math.max(0f,mdivIDerHeight),1f) * height); final SlIDingTabLayout.Tabcolorizer tabcolorizer = mCustomTabcolorizer != null ? mCustomTabcolorizer : mDefaultTabcolorizer; // Thick colored underline below the current selection if (childCount > 0) { VIEw selectedTitle = getChildAt(mSelectedposition); int left = selectedTitle.getleft(); int right = selectedTitle.getRight(); int color = tabcolorizer.getIndicatorcolor(mSelectedposition); if (mSelectionOffset > 0f && mSelectedposition < (getChildCount() - 1)) { int nextcolor = tabcolorizer.getIndicatorcolor(mSelectedposition + 1); if (color != nextcolor) { color = blendcolors(nextcolor,color,mSelectionOffset); } // Draw the selection partway between the tabs VIEw nextTitle = 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(),mBottomborderPaint); // Vertical separators between the Titles int separatortop = (height - divIDerHeightPx) / 2; for (int i = 0; i < childCount - 1; i++) { VIEw child = getChildAt(i); mdivIDerPaint.setcolor(tabcolorizer.getdivIDercolor(i)); canvas.drawline(child.getRight(),separatortop,child.getRight(),separatortop + divIDerHeightPx,mdivIDerPaint); } } /** * Set the Alpha value of the {@code color} to be the given {@code Alpha} value. */ private static int setcolorAlpha(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}. */ private static int blendcolors(int color1,int color2,float ratio) { final float inverseRation = 1f - ratio; float r = (color.red(color1) * ratio) + (color.red(color2) * inverseRation); float g = (color.green(color1) * ratio) + (color.green(color2) * inverseRation); float b = (color.blue(color1) * ratio) + (color.blue(color2) * inverseRation); return color.rgb((int) r,(int) g,(int) b); } private static class SimpleTabcolorizer implements SlIDingTabLayout.Tabcolorizer { private int[] mIndicatorcolors; // private int[] mdivIDercolors; // @OverrIDe public final int getIndicatorcolor(int position) { return mIndicatorcolors[position % mIndicatorcolors.length]; } @OverrIDe public final int getdivIDercolor(int position) { return mdivIDercolors[position % mdivIDercolors.length]; } voID setIndicatorcolors(int... colors) { mIndicatorcolors = colors; } voID setdivIDercolors(int... colors) { mdivIDercolors = colors; } }}
上边因为使用了自定义的颜色,所以这里要在attrs.xml声明一下,不然找不到:
<?xml version="1.0" enCoding="utf-8"?><resources> <declare-styleable name="SlIDingTabLayout"> <attr name="androID:textcolorPrimary" /> <attr name="textcolorTabDefault" format="color" /> <attr name="textcolorTabSelected" format="color" /> </declare-styleable></resources>
布局文件也要用到自定义:
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" xmlns:app="http://schemas.androID.com/apk/res-auto" androID:ID="@+ID/activity_main" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical" tools:context="com.example.my.slIDingtablayout.MainActivity"> <!-- 在上方就在上面,在下方就在下面(tab栏) --> <com.example.my.slIDingtablayout.SlIDingTabLayout androID:ID="@+ID/slIDing" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" app:textcolorTabDefault="#000000" app:textcolorTabSelected="@color/colorAccent" /> <androID.support.v4.vIEw.VIEwPager androID:ID="@+ID/vIEw_pager" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" /></linearLayout>
最后一道就是在你的Activity运用这种开源:可以调整之处也做了说明
package com.example.my.slIDingtablayout;import androID.graphics.color;import androID.os.Bundle;import androID.support.v4.vIEw.PagerAdapter;import androID.support.v4.vIEw.VIEwPager;import androID.support.v7.app.AppCompatActivity;import androID.vIEw.VIEw;import androID.vIEw.VIEwGroup;import androID.Widget.linearLayout;import java.util.ArrayList;public class MainActivity extends AppCompatActivity { //创建 颜色数组 用来做vIEwpager的背景 @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); VIEwPager pager = (VIEwPager) findVIEwByID(R.ID.vIEw_pager); SlIDingTabLayout tab = (SlIDingTabLayout) findVIEwByID(R.ID.slIDing); tab.setdivIDercolors(color.transparent); //设置标题的分割线 tab.setSelectedindicatorcolors(color.rgb(51,181,229)); //设置滚动条的颜色 tab.setTitleSize(18); //...设置字体的颜色,默认16 MyAdapte adapter = new MyAdapte(); pager.setAdapter(adapter); tab.setVIEwPager(pager); } int[] colors = {0xFF123456,0xFF654321,0xFF336699}; class MyAdapte extends PagerAdapter { //可以考虑把这个数组添加到集合里面 String[] Titles = {"AA","BB","CC"}; ArrayList<linearLayout> layouts = new ArrayList<linearLayout>(); MyAdapte() { for (int i = 0; i < 3; i++) { linearLayout l = new linearLayout(MainActivity.this); l.setBackgroundcolor(colors[i]); l.setLayoutParams(new VIEwGroup.LayoutParams(VIEwGroup.LayoutParams.MATCH_PARENT,VIEwGroup.LayoutParams.MATCH_PARENT)); layouts.add(l); } } @OverrIDe public int getCount() { return layouts.size(); } @OverrIDe public boolean isVIEwFromObject(VIEw vIEw,Object o) { return vIEw == o; } @OverrIDe public Object instantiateItem(VIEwGroup container,int position) { linearLayout l = layouts.get(position); container.addVIEw(l); return l; } @OverrIDe public voID destroyItem(VIEwGroup container,int position,Object object) { container.removeVIEw(layouts.get(position)); } @OverrIDe public CharSequence getPageTitle(int position) { //...可以返回集合List.get(position); return Titles[position]; } }}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
以上是内存溢出为你收集整理的AndroidUI组件SlidingTabLayout实现ViewPager页滑动效果全部内容,希望文章能够帮你解决AndroidUI组件SlidingTabLayout实现ViewPager页滑动效果所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)