1. 程式人生 > >【Android開源專案分析】TAB導航欄PagerSlidingTabStrip的使用和原始碼分析

【Android開源專案分析】TAB導航欄PagerSlidingTabStrip的使用和原始碼分析

/* * Copyright (C) 2013 Andreas Stuetz <[email protected]> * * 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.astuetz; 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.graphics.Typeface; 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.Gravity; import android.view.View; import
android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import java.util.Locale; import com.astuetz.pagerslidingtabstrip.R; //繼承HorizontalScrillView,擁有HorizontalScrillView的超出介面時可左右滑動的功能。 public class PagerSlidingTabStrip extends HorizontalScrollView { //通過 viewpager 的 adapter 可以實現介面IconTabProvider public interface IconTabProvider { public int getPageIconResId(int position); } // @formatter:off private static final int[] ATTRS = new int[] { android.R.attr.textSize, android.R.attr.textColor }; // @formatter:on private LinearLayout.LayoutParams defaultTabLayoutParams; private LinearLayout.LayoutParams expandedTabLayoutParams; private final PageListener pageListener = new PageListener(); public OnPageChangeListener delegatePageListener; private LinearLayout tabsContainer; private ViewPager pager; private int tabCount; private int currentPosition = 0; private float currentPositionOffset = 0f; private Paint rectPaint; private Paint dividerPaint; private int indicatorColor = 0xFF666666; private int underlineColor = 0x1A000000; private int dividerColor = 0x1A000000; private boolean shouldExpand = false; private boolean textAllCaps = true; private int scrollOffset = 52; private int indicatorHeight = 8; private int underlineHeight = 2; private int dividerPadding = 12; private int tabPadding = 24; private int dividerWidth = 1; private int tabTextSize = 12; private int tabTextColor = 0xFF666666; private Typeface tabTypeface = null; private int tabTypefaceStyle = Typeface.BOLD; private int lastScrollX = 0; private int tabBackgroundResId = R.drawable.background_tab; private Locale locale; 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); //動態生成橫向的LinearLayout,並新增 tabsContainer = new LinearLayout(context); tabsContainer.setOrientation(LinearLayout.HORIZONTAL); tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); addView(tabsContainer); DisplayMetrics dm = getResources().getDisplayMetrics(); //初始化樣式值(指示器,下劃線,分隔線和TAB文字等樣式) 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); dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm); tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm); dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm); tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm); // get system attrs (android:textSize and android:textColor) TypedArray a = context.obtainStyledAttributes(attrs, ATTRS); tabTextSize = a.getDimensionPixelSize(0, tabTextSize); tabTextColor = a.getColor(1, tabTextColor); a.recycle(); // get custom attrs 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); underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight, underlineHeight); dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsDividerPadding, dividerPadding); tabPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight, tabPadding); tabBackgroundResId = a.getResourceId(R.styleable.PagerSlidingTabStrip_pstsTabBackground, tabBackgroundResId); shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand, shouldExpand); scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_pstsScrollOffset, scrollOffset); 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); //建立兩個LinearLayout.LayoutParams,一個為適應內容長度 defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); //一個為長度比例相同 expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); if (locale == null) { locale = getResources().getConfiguration().locale; } } //繫結ViewPager public void setViewPager(ViewPager pager) { this.pager = pager; //viewpager的adapter不能為空否則會異常, if (pager.getAdapter() == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } //設定了viewpager的OnPageChangeListener,注意是pagerSlidingTabStrip 內部類PageListener pager.setOnPageChangeListener(pageListener); notifyDataSetChanged(); } public void setOnPageChangeListener(OnPageChangeListener listener) { this.delegatePageListener = listener; } //建立TAB導航欄標題,初始化預設第一個標題內容 public void notifyDataSetChanged() { //移除全部子檢視,根據adapter內容addTab tabsContainer.removeAllViews(); tabCount = pager.getAdapter().getCount(); for (int i = 0; i < tabCount; i++) { //如果是 icon 的話,通過 viewpager 的 adapter 實現介面IconTabProvider 否則是 text if (pager.getAdapter() instanceof IconTabProvider) { addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i)); } else { addTextTab(i, pager.getAdapter().getPageTitle(i).toString()); } } updateTabStyles(); 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); } }); } //新增文字TAB導航欄內容 private void addTextTab(final int position, String title) { TextView tab = new TextView(getContext()); tab.setText(title); tab.setGravity(Gravity.CENTER); tab.setSingleLine(); addTab(position, tab); } //新增圖片TAB導航欄內容 private void addIconTab(final int position, int resId) { ImageButton tab = new ImageButton(getContext()); tab.setImageResource(resId); addTab(position, tab); } private void addTab(final int position, View tab) { tab.setFocusable(true); tab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pager.setCurrentItem(position); } }); //設定每個tab左右的padding tab.setPadding(tabPadding, 0, tabPadding, 0); //往container裡面動態新增tab,哪個TabLayoutParams注意看前文 tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams); } //設定每個tab的樣式 @SuppressLint("NewApi") private void updateTabStyles() { for (int i = 0; i < tabCount; i++) { View v = tabsContainer.getChildAt(i); v.setBackgroundResource(tabBackgroundResId); //背景、文字大小、顏色、字型、是否大寫 if (v instanceof TextView) { TextView tab = (TextView) v; tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize); tab.setTypeface(tabTypeface, tabTypefaceStyle); tab.setTextColor(tabTextColor); //API控制 // setAllCaps() is only available from API 14, so the upper case is made manually if we are on a // pre-ICS-build if (textAllCaps) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { tab.setAllCaps(true); } else { tab.setText(tab.getText().toString().toUpperCase(locale)); } } } } } //滾動到特定位置,呼叫父類scrollTo,佈局超出邊界才會起作用 private void scrollToChild(int position, int offset) { if (tabCount == 0) { return; } int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset; if (position > 0 || offset > 0) { newScrollX -= scrollOffset; } //滑動到的位置。 if (newScrollX != lastScrollX) { lastScrollX = newScrollX; scrollTo(newScrollX, 0); } } //onDraw方法繪製分隔線,繪製指示器。 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (isInEditMode() || tabCount == 0) { return; } final int height = getHeight(); // draw indicator line //畫筆顏色 rectPaint.setColor(indicatorColor); // default: line below current tab View currentTab = tabsContainer.getChildAt(currentPosition); float lineLeft = currentTab.getLeft(); float 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) { View nextTab = tabsContainer.getChildAt(currentPosition + 1); final float nextTabLeft = nextTab.getLeft(); final float nextTabRight = nextTab.getRight(); lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft); lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight); } //根據當前tab座標和下一個tab座標和currentPositionOffset計算指示器座標並繪製指示器線 canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint); // draw underline //繪製指示器矩形長條 rectPaint.setColor(underlineColor); canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint); // draw divider //繪製各個tab之間的分隔線長度為dividerPadding 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); } } //內部PageListener類,用於監聽滑動事件得到當前滑動偏移量和當前tab private class PageListener implements OnPageChangeListener { //在此就實現了導航欄會隨著ViewPager滑動而滑動 @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { //當前 view 的位置也即 tab 的位置 currentPosition = position; //當前 view 滑動的距離。其中 currentPositionOffset 為 float,介於 0~1 代表相對於 tab 寬偏移的比例 currentPositionOffset = positionOffset; //根據上面得到的 view 的位置和偏移位置,來同步 tab 的位置和偏移距離。 scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth())); //重繪 view,實現 tab 滑動的效果。 invalidate(); //給pagerslidingtab加滑動監聽delegatePageListener //下面的 delegatePageListener 就是我們設定的 viewpager.setOnPageChangeListener.而現在把它封裝在整個 pagerSlidingTabStrip 中,實現 viewpager 滑動的效果。 if (delegatePageListener != null) { delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } //重寫onPageScrollStateChanged @Override public void onPageScrollStateChanged(int state) { //滑動結束。positionOffset 歸零 if (state == ViewPager.SCROLL_STATE_IDLE) { scrollToChild(pager.getCurrentItem(), 0); } //呼叫 viewpager.setOnPageChangeListener if (delegatePageListener != null) { delegatePageListener.onPageScrollStateChanged(state); } } //重寫onPageSelected @Override public void onPageSelected(int position) { //呼叫 viewpager.setOnPageChangeListener if (delegatePageListener != null) { delegatePageListener.onPageSelected(position); } } } 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 setIndicatorHeight(int indicatorLineHeightPx) { this.indicatorHeight = indicatorLineHeightPx; invalidate(); } public int getIndicatorHeight() { return indicatorHeight; } 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 setUnderlineHeight(int underlineHeightPx) { this.underlineHeight = underlineHeightPx; invalidate(); } public int getUnderlineHeight() { return underlineHeight; } public void setDividerPadding(int dividerPaddingPx) { this.dividerPadding = dividerPaddingPx; invalidate(); } public int getDividerPadding() { return dividerPadding; } 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; } public void setTextSize(int textSizePx) { this.tabTextSize = textSizePx; updateTabStyles(); } public int getTextSize() { return tabTextSize; } public void setTextColor(int textColor) { this.tabTextColor = textColor; updateTabStyles(); } public void setTextColorResource(int resId) { this.tabTextColor = getResources().getColor(resId); updateTabStyles(); } public int getTextColor() { return tabTextColor; } public void setTypeface(Typeface typeface, int style) { this.tabTypeface = typeface; this.tabTypefaceStyle = style; updateTabStyles(); } public void setTabBackground(int resId) { this.tabBackgroundResId = resId; } public int getTabBackground() { return tabBackgroundResId; } public void setTabPaddingLeftRight(int paddingPx) { this.tabPadding = paddingPx; updateTabStyles(); } public int getTabPaddingLeftRight() { return tabPadding; } //activity銷燬時在onSaveInstanceState記錄當前頁數, //當onRestoreInstanceState獲得當前頁數並重新 //requestLayout進行測量、佈局和繪製 @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]; } }; } }

相關推薦

Android開源專案分析TAB導航PagerSlidingTabStrip的使用原始碼分析

/* * Copyright (C) 2013 Andreas Stuetz <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not

Android開源專案解析QQ“一鍵下班”功能實現解析——學習Path及貝塞爾曲線的基本使用

早在很久很久以前,QQ就實現了“一鍵下班”功能。何為“一鍵下班”?當你QQ有資訊時,下部會有資訊數量提示紅點,點選拖動之後,就會出現“一鍵下班”效果。本文將結合github上關於此功能的一個簡單實現,介紹這個功能的基本實現思路。 專案地址

Android開源專案解析背景有波浪效果的TextView——從Titanic專案學習BitmapShader的使用

Hello,好久沒寫文章了,有木有想我呀~ 正式工作已經過去一個月了,發現在青島實習和在北京工作,感覺完全不一樣呢~ 現在每天晚上回到住的地方,都累的想睡覺…所以也沒心情寫太多文章和大家分享了,不過我會盡快調整狀態,重振雄風的!(哪裡起來怪怪的

Android開源專案分析android輕量級開源快取框架——ASimpleCache(ACache)原始碼分析

ASimpleCache框架原始碼連結 官方介紹 ASimpleCache 是一個為android制定的 輕量級的 開源快取框架。輕量到只有一個java檔案(由十幾個類精簡而來)。 1、它可以快取什麼東西? 普通的字串、J

Android開源框架列表

自己一直很喜歡Android開發,就如部落格副標題一樣,我想做個好的App。 http://blog.daimajia.com/android-library-collection/  原文地址 在摸索過程中,GitHub上搜集了很多很棒的Android第三方庫,推薦

kubernetes/k8s原始碼分析 client-go包之Informer原始碼分析

Informer 簡介        Informer 是 Client-go 中的一個核心工具包。如果 Kubernetes 的某個元件,需要 List/Get Kubernetes 中的 Object(包括pod,service等等),可以直接使用

kubernetes/k8s原始碼分析kubectl-controller-manager之job原始碼分析

job介紹     Job: 批量一次性任務,並保證處理的一個或者多個Pod成功結束 非並行Job: 固定完成次數的並行Job: 帶有工作佇列的並行Job: SPEC引數 .spec.completions: 

kubernetes/k8s原始碼分析kubectl-controller-manager之cronjob原始碼分析

crontab的基本格式     支援 , - * / 四個字元           *:表示匹配任意值,如果在Minutes 中使用表示每分鐘    &

kubernetes/k8s原始碼分析kubectl-controller-manager之HPA原始碼分析

本文基於kubernetes版本:v1.12.1 HPA介紹      https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/     Th

Flume原始碼分析flume中攔截器的原始碼分析,以TimestampInterceptor為例

本文將以TimestampInterceptor為例來分析一下flume中攔截器的工作原理 首先來看下改攔截器的實現結構 1、實現了Interceptor介面 該介面的方法定義如下: public void initialize(); public Event in

開源Android開源專案:始終

介,,介紹 內個什麼,這是一個 Android 平臺的 APP,專案基於 RxAndroid+Retrofit+Glide 開發,使用MVP架構(好像大家都喜歡這麼寫…)。 最近經濟什麼的不太好大家都知

AndroidAndroid開源專案(一)音樂播放器原始碼彙總

作為一個有追求的程式設計師來說,專案原始碼必須看,但是網上那麼多資源是不讓你無從下手啊,博主今天為大家推薦五個經典專案吧。 一、android-UniversalMusicPlayer 這個開源專案展示瞭如何實現一個橫跨各種Android平臺的音樂播放器,包

Android 應用開發GitHub 優秀的 Android 開源專案

主要介紹那些不錯個性化的View,包括ListView、ActionBar、Menu、ViewPager、Gallery、GridView、ImageView、ProgressBar及其他如Dialog、Toast、EditText、TableView、Ac

Android開源美團等APP城市選擇

data- pac 就是 blank all ike 需要 高德 city CityPicker 現在使用比較多的類似美團等APP的城市選擇界面. 2步即可實現,就是這麽簡單粗暴! Gif image APK 下載demo.apk體驗. Install Gradle

android睡眠喚醒 一MTK 喚醒時間分析

一、喚醒流程:   MTK平臺喚醒流程是從power鍵或者其他按鍵按下開始,本文以mt6753n平臺為例,通過分析kernel log來看驅動中整個喚醒的流程,上層的喚醒流程後續再分析。 1、按鍵按下   當按鍵按下時會出發中斷,從而回調中斷的處理函式,從kernel log從會有以下

學以致用android功能實現7---android8.0 Launcher獲取快捷方式原始碼分析(3)

獲取完快捷方式的資訊之後,便是如何具體的將快捷方式的名字,圖示和開啟方式放置到桌面上。 最後一步addAndBindAddedWorkspaceItems(                 new LazyShortcutsProvider(context.getAppl

第三方開源專案MD 風格的對話方塊 —— MaterialDialog

定義: MaterialDialog:一個漂亮、流暢、可定製的對話方塊。 依賴: 核心模組的依賴: compile 'com.afollestad.material-dialogs:core:0.9.6.0' 核心模組包含該庫的所有主要類,

Android實戰專案Odoo 郵箱客戶端的經歷

在技術層面上來說,我在開發這款APP的時候,只是個大三的學生,經驗上和技術上都不成熟,現在大四,把之前做的Odoo 郵箱拿出來總結一下,和大家分享一下, 在漫長的開發中,也發現了很多新人都會犯的毛病,大部分人都太強調實踐操作,而疏忽了多看書總結經驗,由於是企業應用,全部原始

Android 技術難點攻克RecyclerView實現懸停導航

介紹在上一篇文章《》中,我講述瞭如何解決ScrollView與RecyclerView的滑動衝突問題。時隔幾個月,我對這樣的程式結構有很多的反思。當初這樣巢狀,其實最主要是為了實現懸停。那麼懸停的最好的

學以致用android功能實現5---android8.0 Launcher獲取快捷方式原始碼分析(1)

從其他應用往桌面建立快捷方式,android8.0統一採用requestPinShortcut的方式。 對於桌面而言,是怎麼從requestPinShortcut獲取快捷方式資訊在桌面建立快捷方式呢? Android8.0的快捷方式引數不再通過廣播傳送,而是存放在系統當中