Android tab切換控制元件
阿新 • • 發佈:2019-01-05
基於viewpager,實現了可以點選tab,可頁面左右滑動,tab變化,tab下標動畫等。
分為四個部分:
第一個FragTabsViewPager,讓您想要實現的頁面繼承它。
相應的xml檔案,frag_tabs_viewpager:package com.base; import java.util.List; import com.shennongshi.dingdong.R; import com.third.widget.PagerSlidingTabStrip; import com.utils.data.PhoneInfo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public abstract class FragTabsViewPager extends FragBase { protected View mView; protected boolean mIsDrawDivider = true; public ViewPager mViewPager; protected static int mTabPaddingLeftRight = (int) (PhoneInfo.convertDpToPx(2)); @Override protected View initContainerView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.frag_tabs_viewpager, container, false); mViewPager = initViewPager(mView); initTabs(mView); return mView; } protected abstract List<View> getIndicatorViews(); protected abstract List<Class<?>> getFragClasses(); protected abstract List<Bundle> getBundles(); protected ViewPager initViewPager(View view) { ViewPager viewPager = (ViewPager) view.findViewById(R.id.pager); FragmentActivity act = getActivity(); FragTabsAdapter adapter = new FragTabsAdapter(act, getChildFragmentManager(), getFragClasses(), getBundles()); viewPager.setAdapter(adapter); return viewPager; } protected void initTabs(View view) { PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs); List<View> tabViews = getIndicatorViews(); int count = 0; if (tabViews != null) count = tabViews.size(); tabs.setShouldExpand(true); tabs.setUnderlineColorResource(R.color.background); tabs.setIndicatorColorResource(R.color.mainblue); tabs.setViewPager(mViewPager); for (int i = 0; i < count; i++) { tabs.addTab(i, tabViews.get(i)); } if (tabViews.size() > 0) tabViews.get(0).setSelected(true); } }
tab動畫類PagerSlidingTabStrip:<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#e7edef" android:orientation="vertical" > <include layout="@layout/pagerslidingtabstrip" /> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
package com.third.widget; import com.shennongshi.dingdong.R; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.View; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; public class PagerSlidingTabStrip extends HorizontalScrollView { protected LinearLayout.LayoutParams defaultTabLayoutParams; protected LinearLayout.LayoutParams expandedTabLayoutParams; protected final PageListener pageListener = new PageListener(); public OnPageChangeListener delegatePageListener; protected LinearLayout tabsContainer; protected ViewPager pager; protected int tabCount; protected int currentPosition = 0; protected float currentPositionOffset = 0f; private Paint dividerPaint; protected Paint rectPaint; protected int indicatorColor = 0xFF666666; protected int underlineColor = 0x1A000000; protected int dividerColor = 0x1A000000; protected boolean shouldExpand = false; protected boolean textAllCaps = true; protected boolean drawDivider = false; protected int scrollOffset = 52; protected int indicatorHeight = 8; protected int underlineHeight = 2; private int dividerPadding = 12; private int dividerWidth = 1; protected int lastScrollX = 0; public PagerSlidingTabStrip(Context context) { this(context, null); } public PagerSlidingTabStrip(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setFillViewport(true); setWillNotDraw(false); tabsContainer = new LinearLayout(context); tabsContainer.setOrientation(LinearLayout.HORIZONTAL); tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); addView(tabsContainer); DisplayMetrics dm = getResources().getDisplayMetrics(); scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm); indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm); underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip); indicatorColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsIndicatorColor, indicatorColor); underlineColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsUnderlineColor, underlineColor); dividerColor = a.getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor, dividerColor); indicatorHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight, indicatorHeight); dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsDividerPadding, dividerPadding); underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight, underlineHeight); shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand, shouldExpand); scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsScrollOffset, scrollOffset); dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm); textAllCaps = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps); a.recycle(); rectPaint = new Paint(); rectPaint.setAntiAlias(true); rectPaint.setStyle(Style.FILL); dividerPaint = new Paint(); dividerPaint.setAntiAlias(true); dividerPaint.setStrokeWidth(dividerWidth); defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); } public void setViewPager(ViewPager pager) { this.pager = pager; if (pager.getAdapter() == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } pager.setOnPageChangeListener(pageListener); notifyDataSetChanged(); } public void setOnPageChangeListener(OnPageChangeListener listener) { this.delegatePageListener = listener; } public void notifyDataSetChanged() { tabCount = pager.getAdapter().getCount(); getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { getViewTreeObserver().removeOnGlobalLayoutListener(this); } currentPosition = pager.getCurrentItem(); scrollToChild(currentPosition, 0); } }); } public void addTab(final int position, View tab) { tab.setFocusable(true); tab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(tabsContainer.getChildCount() != 0){ tabsContainer.getChildAt(currentPosition).setSelected(false); tabsContainer.getChildAt(position).setSelected(true); pager.setCurrentItem(position); } } }); tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams); } private void scrollToChild(int position, int offset) { if (tabCount == 0) { return; } int newScrollX = 0; if(tabsContainer.getChildCount() != 0) newScrollX = tabsContainer.getChildAt(position).getLeft() + offset; if (position > 0 || offset > 0) { newScrollX -= scrollOffset; } if (newScrollX != lastScrollX) { lastScrollX = newScrollX; scrollTo(newScrollX, 0); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (isInEditMode() || tabCount == 0) { return; } final int height = getHeight(); // default: line below current tab float lineLeft = 0; float lineRight = 0; if(tabsContainer.getChildCount() != 0){ View currentTab = tabsContainer.getChildAt(currentPosition); lineLeft = currentTab.getLeft(); lineRight = currentTab.getRight(); } // if there is an offset, start interpolating left and right coordinates between current and next tab if (currentPositionOffset > 0f && currentPosition < tabCount - 1) { float nextTabLeft = 0; float nextTabRight = 0; if(tabsContainer.getChildCount() != 0){ View nextTab = tabsContainer.getChildAt(currentPosition + 1); nextTabLeft = nextTab.getLeft(); nextTabRight = nextTab.getRight(); } lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft); lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight); } // draw indicator line rectPaint.setColor(indicatorColor); canvas.drawRect(lineLeft + 70, height - indicatorHeight, lineRight - 70, height, rectPaint); // draw underline rectPaint.setColor(underlineColor); canvas.drawRect(0, height - 3 *underlineHeight, tabsContainer.getWidth(), height , rectPaint); // draw divider if (drawDivider) { dividerPaint.setColor(dividerColor); for (int i = 0; i < tabCount - 1; i++) { View tab = tabsContainer.getChildAt(i); canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint); } } } private class PageListener implements OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (currentPosition != position) { View oldTab = tabsContainer.getChildAt(currentPosition); View newTab = tabsContainer.getChildAt(position); oldTab.setSelected(false); newTab.setSelected(true); } currentPosition = position; currentPositionOffset = positionOffset; if(tabsContainer.getChildCount() != 0) scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth())); invalidate(); if (delegatePageListener != null) { delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_IDLE) { scrollToChild(pager.getCurrentItem(), 0); } if (delegatePageListener != null) { delegatePageListener.onPageScrollStateChanged(state); } } @Override public void onPageSelected(int position) { if (delegatePageListener != null) { delegatePageListener.onPageSelected(position); } } } public void setDrawDivider(boolean divider) { this.drawDivider = divider; invalidate(); } public void setIndicatorColor(int indicatorColor) { this.indicatorColor = indicatorColor; invalidate(); } public void setIndicatorColorResource(int resId) { this.indicatorColor = getResources().getColor(resId); invalidate(); } public int getIndicatorColor() { return this.indicatorColor; } public void setUnderlineColor(int underlineColor) { this.underlineColor = underlineColor; invalidate(); } public void setUnderlineColorResource(int resId) { this.underlineColor = getResources().getColor(resId); invalidate(); } public int getUnderlineColor() { return underlineColor; } public void setDividerColor(int dividerColor) { this.dividerColor = dividerColor; invalidate(); } public void setDividerColorResource(int resId) { this.dividerColor = getResources().getColor(resId); invalidate(); } public int getDividerColor() { return dividerColor; } public void setIndicatorHeight(int indicatorLineHeightPx) { this.indicatorHeight = indicatorLineHeightPx; invalidate(); } public int getIndicatorHeight() { return indicatorHeight; } public void setUnderlineHeight(int underlineHeightPx) { this.underlineHeight = underlineHeightPx; invalidate(); } public int getUnderlineHeight() { return underlineHeight; } public void setScrollOffset(int scrollOffsetPx) { this.scrollOffset = scrollOffsetPx; invalidate(); } public int getScrollOffset() { return scrollOffset; } public void setShouldExpand(boolean shouldExpand) { this.shouldExpand = shouldExpand; requestLayout(); } public boolean getShouldExpand() { return shouldExpand; } public boolean isTextAllCaps() { return textAllCaps; } public void setAllCaps(boolean textAllCaps) { this.textAllCaps = textAllCaps; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); currentPosition = savedState.currentPosition; requestLayout(); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.currentPosition = currentPosition; return savedState; } static class SavedState extends BaseSavedState { int currentPosition; public SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentPosition = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(currentPosition); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
然後相應的xml檔案pagerslidingtabstrip:
<?xml version="1.0" encoding="utf-8"?>
<com.third.widget.PagerSlidingTabStrip
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:psts="http://schemas.android.com/apk/res/com.shennongshi.dingdong"
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
psts:pstsIndicatorHeight="3dp"
psts:pstsUnderlineHeight="0.3dp" />
下面舉例使用:這個fragment繼承了fragtabviewpager。
package com.shennongshi.dingdong.ui.xuewen.liebiao;
import java.util.ArrayList;
import java.util.List;
import com.base.ActBase;
import com.base.ActGuide;
import com.base.FragTabsAdapter;
import com.base.FragTabsViewPager;
import com.base.ViewTitle;
import com.shennongshi.dingdong.R;
import com.shennongshi.dingdong.ui.fanganliebiao1.FragFALB1;
import com.shennongshi.dingdong.ui.fanganliebiao2.FragFALB2;
import com.shennongshi.dingdong.ui.fanganliebiao3.FragFALB3;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
/**
* @author lrz
* xuewen
*/
public class FragXuewenliebiao extends FragTabsViewPager {
private FragWYHD fragWYHD;
private FragWDTW fragWDTW;
private FragWDHD fragWDHD;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected View initContainerView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= super.initContainerView(inflater, container, savedInstanceState);
return view;
}
}
@Override
protected List<View> getIndicatorViews() {
List<View> views=new ArrayList<View>(3);
ViewGroup view=(ViewGroup) ViewGroup.inflate(getActivity(), R.layout.frag_xuewen_header, null);
View frag_xuewen_WYHD =view.findViewById(R.id.frag_xuewen_WYHD);
views.add(frag_xuewen_WYHD);
view.removeView(frag_xuewen_WYHD);
View frag_xuewen_WDTW =view.findViewById(R.id.frag_xuewen_WDTW);
views.add(frag_xuewen_WDTW);
view.removeView(frag_xuewen_WDTW);
View frag_xuewen_WDHD =view.findViewById(R.id.frag_xuewen_WDHD);
views.add(frag_xuewen_WDHD);
view.removeView(frag_xuewen_WDHD);
return views;
}
@Override
protected List<Class<?>> getFragClasses() {
List<Class<?>> frags = new ArrayList<Class<?>>(3);
frags.add(FragWYHD.class);
frags.add(FragWDTW.class);
frags.add(FragWDHD.class);
return frags;
}
@Override
protected List<Bundle> getBundles() {
// TODO Auto-generated method stub
return null;
}
}