編輯:關於 Android 程式設計
本篇要動手做一個自定義的 CircleIndicator 控制項;下一篇再談如何改寫 ViewPager 的切換效果,預計明晚之前更新。





接入只需兩步。
第一步,寫在 XML 布局裡:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.xujun.administrator.customviewspecif.view.CirclePageIndicator
android:id="@+id/circle_indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp" />
</RelativeLayout>
第二步,寫在程式碼裡:
mViewPager = (ViewPager) findViewById(R.id.viewPager); mCirclePageIndicator = (CirclePageIndicator) findViewById(R.id.circle_indicator); // 注意下面初始化的順序不可調換 mFragemntAdapter = new BaseFragemntAdapter(getSupportFragmentManager(), mFragments); mViewPager.setAdapter(mFragemntAdapter); // 把 CirclePageIndicator 與 ViewPager 綁定 mCirclePageIndicator.setViewPager(mViewPager);
1)在 XML 中調整外觀:
xmlns:app="https://schemas.android.com/apk/res-auto"
// 例如改掉移動小圓點的顏色
app:fillColor="#fff"
// 其餘可自定義屬性如下
<declare-styleable name="CirclePageIndicator">
<!-- Whether or not the indicators should be centered. -->
<!-- Color of the filled circle that represents the current page. -->
<!-- Color of the filled circles that represents pages. -->
<!-- Orientation of the indicator. -->
<!-- Radius of the circles. This is also the spacing between circles. -->
<!-- Whether or not the selected indicator snaps to the circles. -->
<!-- Color of the open circles. -->
<!-- Width of the stroke used to draw the circles. -->
<!-- View background -->
</declare-styleable>
2)在 Java 程式碼中動態調整:
// 滑動時小圓點是否跳躍 mCirclePageIndicator.setSnap(false); // 小圓點半徑 mCirclePageIndicator.setRadius(10 * density); // 頁面小圓點顏色 mCirclePageIndicator.setPageColor(0x880000FF); // 移動小圓點顏色 mCirclePageIndicator.setFillColor(0xFF888888); // 外框顏色 mCirclePageIndicator.setStrokeColor(0xFF000000); // 外框寬度 mCirclePageIndicator.setStrokeWidth(2 * density);
大致分為五個步驟。
(1)繼承 View,在建構子裡完成初始化,包括讀取自定義屬性與建立畫筆。
public CirclePageIndicator(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (isInEditMode()) return;
// 初始化自定義屬性
final Resources res = getResources();
final int defaultPageColor = res.getColor(R.color.default_circle_indicator_page_color);
final int defaultFillColor = res.getColor(R.color.default_circle_indicator_fill_color);
final int defaultOrientation = res.getInteger(R.integer.default_circle_indicator_orientation);
// ... 此處省略若干方法
a.recycle();
final ViewConfiguration configuration = ViewConfiguration.get(context);
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
}
(2)在 onMeasure 中依方向不同量出尺寸。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == HORIZONTAL) {
setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec));
} else {
setMeasuredDimension(measureShort(widthMeasureSpec), measureLong(heightMeasureSpec));
}
}
/**
* Determines the width of this view
*/
private int measureLong(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if ((specMode == MeasureSpec.EXACTLY) || (mViewPager == null)) {
// We were told how big to be
result = specSize;
} else {
// Calculate the width according the views count
final int count = mViewPager.getAdapter().getCount();
result = (int) (getPaddingLeft() + getPaddingRight()
+ (count * 2 * mRadius) + (count - 1) * mRadius + 1);
// Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
/**
* Determines the height of this view
*/
private int measureShort(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the height
result = (int) (2 * mRadius + getPaddingTop() + getPaddingBottom() + 1);
// Respect AT_MOST value if that was what is called for by measureSpec
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
(3)提供 setViewPager(ViewPager view) 把兩者綁在一起。
@Override
public void setViewPager(ViewPager view) {
if (mViewPager == view) {
return;
}
if (mViewPager != null) {
mViewPager.addOnPageChangeListener(null);
}
if (view.getAdapter() == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
mViewPager = view;
mViewPager.addOnPageChangeListener(this);
invalidate();
}
邏輯很直白:先確認 ViewPager 已經設好 adapter,沒有就拋異常;接著掛上 PageChangeListener,最後 invalidate() 觸發重繪。
(4)在 ViewPager 滑動時取得對應的偏移量。
@Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mListener != null) {
mListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
mCurrentPage = position;
mPageOffset = positionOffset;
invalidate();
if (mListener != null) {
mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageSelected(int position) {
if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mCurrentPage = position;
mSnapPage = position;
invalidate();
}
if (mListener != null) {
mListener.onPageSelected(position);
}
}
(5)在 onDraw 中依偏移量把小圓點畫出來。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mViewPager == null) {
return;
}
final int count = mViewPager.getAdapter().getCount();
if (count == 0) {
return;
}
if (mCurrentPage >= count) {
setCurrentItem(count - 1);
return;
}
int longSize;
int longPaddingBefore;
int longPaddingAfter;
int shortPaddingBefore;
// 依方向不同初始化各個變量
if (mOrientation == HORIZONTAL) {
longSize = getWidth();
longPaddingBefore = getPaddingLeft();
longPaddingAfter = getPaddingRight();
shortPaddingBefore = getPaddingTop();
} else {
longSize = getHeight();
longPaddingBefore = getPaddingTop();
longPaddingAfter = getPaddingBottom();
shortPaddingBefore = getPaddingLeft();
}
final float threeRadius = mRadius * 3;
final float shortOffset = shortPaddingBefore + mRadius;
float longOffset = longPaddingBefore + mRadius;
// 居中顯示
if (mCentered) {
longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f)
- ((count * threeRadius) / 2.0f);
}
float dX;
float dY;
float pageFillRadius = mRadius;
if (mPaintStroke.getStrokeWidth() > 0) {
pageFillRadius -= mPaintStroke.getStrokeWidth() / 2.0f;
}
// Draw stroked circles
for (int iLoop = 0; iLoop < count; iLoop++) {
float drawLong = longOffset + (iLoop * threeRadius);
if (mOrientation == HORIZONTAL) {
dX = drawLong;
dY = shortOffset;
} else {
dX = shortOffset;
dY = drawLong;
}
// Only paint fill if not completely transparent
if (mPaintPageFill.getAlpha() > 0) {
canvas.drawCircle(dX, dY, pageFillRadius, mPaintPageFill);
}
// Only paint stroke if a stroke width was non-zero
if (pageFillRadius != mRadius) {
canvas.drawCircle(dX, dY, mRadius, mPaintStroke);
}
}
// 畫出移動中的實心圓
float cx = (mSnap ? mSnapPage : mCurrentPage) * threeRadius;
// 依是否跳躍決定要不要疊加偏移量
if (!mSnap) {
cx += mPageOffset * threeRadius;
}
if (mOrientation == HORIZONTAL) {
dX = longOffset + cx;
dY = shortOffset;
} else {
dX = shortOffset;
dY = longOffset + cx;
}
canvas.drawCircle(dX, dY, mRadius, mPaintFill);
}
核心其實就是依方向把圓點一個個畫出來,剩下的都是偏移量的數學運算。別小看這些計算,真要一筆一筆推,還是相當繁瑣。
源碼分析到此為止。
限時搶購秒殺系統架構深度剖析與實戰指南
秒殺(限時搶購)是電商領域最典型的高並發場景之一:低價促銷、大量推廣、瞬間售空、定時上架,時間短但瞬時並發量極高。這類系統對架構設計提出了嚴苛考驗。本文將從業務分析、技術
Android 版「QQ 桌面」值得一試的實用小技巧
騰訊把「手機 QQ 桌面」帶到了 Android 平台。這個版本除了關注城市天氣與資訊熱點,還能在桌面直接收發 QQ 訊息,並打造屬於自己的待機桌面。這篇就來看看新版手機
Android 資料傳遞筆記(三):用介面回呼把 Activity 的資料送進 Fragment
Activity 與 Fragment 之間要交換資料,做法其實不少,但最常見、也最能體現解耦思想的一種,就是「介面回呼」(Interface Callback)。本文用
Android 進程間通訊四大方式詳解:Intent、廣播、ContentProvider 與 AIDL
同一個 App 內的頁面跳轉大家都熟,但一旦要跨進程(跨 App)交換資料,就得換一套工具。Android 提供了幾條標準路徑:Intent 的 ComponentNam