編輯:關於 Android 程式設計
近期專案需要用到滑動式頁面切換,效果類似目前很紅的「今日頭條」。上網查資料後發現,大多數實作都是採用 ViewPager。最初我嘗試的是 ViewPager + ViewGroup 的組合,頂部標題按鈕用 HorizontalScrollView,寫完之後感覺切換略顯生硬,於是果斷換掉,找到了一款效果更順暢的第三方元件,也就是今天的主角:PagerSlidingTabStrip。下面會逐一介紹它,並做一點源碼解析。


接著在佈局檔案中進行宣告:
<span ><?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res/com.hankkin.PagerSlidingTabStrip" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.hankkin.PagerSlidingTabStrip.view.PagerSlidingTabStrip android:id="@+id/tab" app:pstsShouldExpand="false" app:pstsUnderlineHeight="2dp" app:pstsIndicatorHeight="2dp" app:pstsIndicatorColor="@android:color/holo_blue_light" app:selectedTabTextColor="@android:color/holo_blue_light" app:pstsDividerColor="@android:color/transparent" app:pstsTabBackground="@drawable/background" android:background="@android:color/white" android:layout_width="match_parent" android:layout_height="55dp"/> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout></span><span > </span>
上方是滑動式的標題標籤,下方的 ViewPager 則用來承載各頁內容。
<span >package com.hankkin.PagerSlidingTabStrip.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.hankkin.PagerSlidingTabStrip.fragment.AndroidFragment; import com.hankkin.PagerSlidingTabStrip.fragment.JavaFragment; import com.hankkin.PagerSlidingTabStrip.fragment.ObjectCFragment; import java.util.List; public class MyAdapter extends FragmentPagerAdapter { private AndroidFragment androidFragment; private JavaFragment javaFragment; private ObjectCFragment objectCFragment; private String[] titles; public MyAdapter(FragmentManager fm,String[] titles) { super(fm); this.titles = titles; } @Override public Fragment getItem(int position) { switch (position) { case 0: if (androidFragment == null) { androidFragment = new AndroidFragment(); } return androidFragment; case 1: if (javaFragment == null) { javaFragment = new JavaFragment(); } return javaFragment; case 2: if (objectCFragment == null) { objectCFragment = new ObjectCFragment(); } return objectCFragment; default: return null; } } @Override public int getCount() { return titles.length; } public String getPageTitle(int i){ return titles[i]; } } </span>
這裡使用的是 Fragment,最下方的 getPageTitle() 是 PagerSlidingTabStrip 提供的方法,用來取得各頁標題。
接著初始化 PagerSlidingTabStrip、ViewPager 以及各個 Fragment。
<span > private void initViews(){ fragments = new ArrayList<>(); pagerTab = (PagerSlidingTabStrip) findViewById(R.id.tab); pager = (ViewPager) findViewById(R.id.pager); for (int i=0;i<titles.length;i++){ Fragment fragment = new Fragment(); fragments.add(fragment); } adapter = new MyAdapter(getSupportFragmentManager(),titles); pager.setAdapter(adapter); pagerTab.setViewPager(pager); }</span>
在 Adapter 中,透過 FragmentManager 把各 Fragment 與標題一一對應。這裡要提醒的是:若 Fragment 數量不多,可以手動建立;但若像今日頭條那樣數量龐大也無妨,因為各頁內容大致相似,動態建立完全可行,只有個別特殊的頁面再單獨處理即可。
如此簡單就實現了類似頭條的滑動效果。下面一起看看 PagerSlidingTabStrip 的源碼,理解之後也方便我們做進一步的改良。
先看幾個比較關鍵的屬性:
private int indicatorColor = 0xFF666666;// 滑動指示器顏色 private int underlineColor = 0x1A000000;//在視圖的底部的全寬度的線pstsunderlinecolor顏色 private int dividerColor = 0x1A000000;//選項卡之間的分隔pstsdividercolor顏色 private boolean shouldExpand = false;//pstsshouldexpand如果設置為TRUE,每個標簽都給予同樣的重量,默認為false private boolean textAllCaps = true;//pststextallcaps如果為真,所有選項卡標題都是大寫,默認為true private int scrollOffset = 52;//pstsscrolloffset卷軸被選擇的標簽的偏移 private int indicatorHeight = 8;//滑動指示器pstsindicatorheight private int underlineHeight = 2;//在視圖的底部的全寬度的線pstsunderlineheight高度 private int dividerPadding = 12;//pstsdividerpadding頂部和底部填充的分頻器 private int tabPadding = 24;//pststabpaddingleftright左、右填充每個選項卡 private int dividerWidth = 1;//選項卡分割線寬度 private int tabTextSize = 12;//選項卡字體大小 private int tabTextColor = 0xFF666666;//選項卡字體顏色 private int selectedTabTextColor = 0xFF666666;//當前選中字體顏色 private Typeface tabTypeface = null; private int tabTypefaceStyle = Typeface.NORMAL; private int lastScrollX = 0; private int tabBackgroundResId = R.drawable.background;//pststabbackground背景繪制的每個標簽,應該是一個statelistdrawable
這些屬性的值都可以自行覆寫,畢竟預設值未必符合每個專案的視覺需求。
1. 建構子在初始化時會設定哪些屬性
<span >public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setFillViewport(true);//默認使子view可以拉伸來填滿整個屏幕 setWillNotDraw(false);//默認不執行OnDraw()方法 //初始化盛放按鈕標題的線性布局 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); 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); //tab文字選中時的顏色,默認和滑動指示器的顏色一致 selectedTabTextColor=a.getColor(R.styleable.PagerSlidingTabStrip_selectedTabTextColor, 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); 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; } }</span>
這部分主要是初始化各項屬性,程式碼中也有相應註解,就不逐一展開了。
2. 定義 ViewPager 的滑動監聽器,並設定當前頁位置
<span >private class PageListener implements OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { currentPosition = position; currentPositionOffset = positionOffset; 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) { selectedPosition = position; updateTabStyles(); if (delegatePageListener != null) { delegatePageListener.onPageSelected(position); } } }</span>
3. 更新標題樣式,也就是切換到當前標籤時改變其狀態
<span >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); // 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)); } } if (i == selectedPosition) { tab.setTextColor(selectedTabTextColor); } } } }</span>
大體上就是這些。最後給大家看看我微調之後的樣子。

其實沒做太多調整,只是稍微改了樣式。裡面還有一些細節沒有展開,例如標題寬度是平均分配,還是依文字長度個別設定——這可以透過 shouldExpand 屬性來控制,有興趣的朋友不妨自行深入研究。
Mac 上 Eclipse 無法偵測 Android 手機的完整解法
同一支手機在 Windows 的 Eclipse 裡 Device 清單看得到名稱,換到 Mac OS X 卻遲遲不顯示——這是 Mac 開發 Android 最常見的障
從搶紅包插件說起:AccessibilityService 的玩法與風險
微信紅包自誕生起就人氣爆棚,搶紅包插件也隨之風靡一時。今天我們回頭拆解一下它的原理。老實說並不複雜:本質上就是在收到紅包通知時,自動完成一連串點擊——做過自動化 UI 測
AndResGuard 資源混淆工具完整使用指南與效能解析
本文整理自專案開源說明文件(github.com/shwenzhang/AndResGuard)。AndResGuard 是一款專注於 APK 資源混淆的工具,它並不介入
徹底搞懂 Canvas clipRect 與 Region.Op 各個參數
clipRect 是 Canvas 上做裁剪的核心方法,而它的重載版本 clipRect(Rect, Region.Op) 的第二個參數,是很多人寫了兩年 Android