Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

動手寫一個 Android 桌面滑動切換螢幕的控件(二)

編輯:關於 Android 程式設計

上一篇把骨架、測量、佈局與觸控都搭好了,這篇來補上剩下幾個關鍵環節:動畫驅動、效能優化、跨頁預繪製,以及底部指示點。

一、對頁動畫的起點

在 ViewGroup 中實作對頁:

public void snapToScreen(int whichScreen) {
    whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
    boolean changingScreens = whichScreen != mCurrentScreen;
    mNextScreen = whichScreen;

    int mScrollX = this.getScrollX();
    final int newX = whichScreen * getWidth();
    final int delta = newX - mScrollX;

    // 從 x 座標 mScrollX 的位置滑動 delta 距離
    mScroller.startScroll(mScrollX, 0, delta, 0, Math.abs(delta) * 2);

    // invalidate 非常重要,否則輕微移動後頁面無法復原
    invalidate();
}

二、重寫 computeScroll 讓動畫真正跑起來

只呼叫 startScroll 是不夠的,必須搭配 computeScroll 才有連續的位移效果:

@Override
public void computeScroll() {
    if (mScroller.computeScrollOffset()) {
        scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
        postInvalidate();
    } else if (mNextScreen != -1) {
        // 滑動完成後才執行這裡,此時必須設定當前頁
        setCurrentScreen(Math.max(0, Math.min(mNextScreen, getChildCount() - 1)));
        mNextScreen = -1;
    }
}

三、效能優化:只讓當前頁可見

如果一次載入太多子控制項,效能會明顯下降。解法是只顯示當前頁,其餘設為不可見:

void setCurrentScreen(int index) {
    mCurrentScreen = index;
    resetVisibilityForChildren();
}

private void resetVisibilityForChildren() {
    int count = getChildCount();
    for (int i = 0; i < count; i++) {
        View child = getChildAt(i);
        if (Math.abs(mCurrentScreen - i) <= 0) {
            child.setVisibility(View.VISIBLE);
        } else {
            child.setVisibility(View.INVISIBLE);
        }
    }
}

四、重寫 dispatchDraw:滑動時把隔壁頁也畫出來

既然非當前頁被設為不可見,滑動過程中就會出現空白。解法是在繪製階段主動把左右兩頁都畫上:

@Override
protected void dispatchDraw(Canvas canvas) {
    int childCount = getChildCount();
    if (childCount == 0) {
        return;
    }
    boolean restore = false;
    int restoreCount = 0;

    final long drawingTime = getDrawingTime();
    final float scrollPos = (float) getScrollX() / getWidth();
    final int leftScreen = (int) scrollPos;
    final int rightScreen = leftScreen + 1;

    if (leftScreen >= 0 && leftScreen < childCount) {
        // 這會讓 leftScreen 從不可見狀態顯示出來
        drawChild(canvas, getChildAt(leftScreen), drawingTime);
    }
    if (rightScreen < getChildCount()) {
        drawChild(canvas, getChildAt(rightScreen), drawingTime);
    }

    if (restore) {
        canvas.restoreToCount(restoreCount);
    }
}

五、加入底部指示點

先在 MyGroup 類裡定義回呼介面與更新邏輯:

public void setmListener(OnViewChangedListener mListener) {
    this.mListener = mListener;
}

public interface OnViewChangedListener {
    /**
     * 視圖切換時回呼。
     * @param viewIndex 索引
     */
    void onViewChanged(int viewIndex);
}

private static final int DEFAULT_POINT_MARGIN = 5;

/**
 * 更新指示點狀態,包括總數與當前位置。
 *
 * @param dotsLayout 用來放置指示點的 layout
 * @param total      總數
 * @param current    當前位置
 * @param state      Bundle 參數擴展,可為 null
 */
public static void updateDots(ViewGroup dotsLayout, int total, int current, Bundle state) {
    if (total < 0) {
        total = 0;
    }

    int lastIndex = -1;
    Object tag = dotsLayout.getTag(R.id.dots_current);
    if (tag != null) {
        lastIndex = (Integer) tag;
    }

    int margin = DEFAULT_POINT_MARGIN;
    if (state != null) {
        margin = state.getInt(KEY_POINT_MARGIN, margin);
    }

    int childrenNum = dotsLayout.getChildCount();
    for (int i = childrenNum; i < total; i++) {
        ImageView pointView = new ImageView(dotsLayout.getContext());
        pointView.setImageResource(R.drawable.dot);
        dotsLayout.addView(pointView);
        LinearLayout.LayoutParams params =
                (LinearLayout.LayoutParams) pointView.getLayoutParams();
        params.leftMargin = margin;
        params.rightMargin = margin;
    }
    for (int i = childrenNum - 1; i >= total; i--) {
        dotsLayout.removeViewAt(i);
    }

    if (current == lastIndex) {
        return;
    }
    if (lastIndex >= 0 && lastIndex < total) {
        ImageView pointView = (ImageView) dotsLayout.getChildAt(lastIndex);
        pointView.setImageResource(R.drawable.dot);
    }
    if (current >= 0 && current < total) {
        ImageView pointView = (ImageView) dotsLayout.getChildAt(current);
        pointView.setImageResource(R.drawable.dot_current);
    }
    dotsLayout.setTag(R.id.dots_current, current);
}

public interface WorkspaceSnapListener {
    void onSnapToScreen(MyGroup workspace, int whichScreen);
}

public void setSnapListener(WorkspaceSnapListener listener) {
    snapListener = listener;
}

接著在兩個時機點觸發回呼:

@Override
public void computeScroll() {
    if (mScroller.computeScrollOffset()) {
        // ...
    } else if (mNextScreen != -1) {
        if (mListener != null) {
            mListener.onViewChanged(mCurrentScreen);
        }
    }
}

public void snapToScreen(int whichScreen) {
    if (snapListener != null) {
        snapListener.onSnapToScreen(this, whichScreen);
    }
    // ...
}

六、佈局與指示點的樣式

<FrameLayout android:id="@+id/MainRoot"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <com.ringcentral.android.utils.ui.widget.mygroup
        android:background="@drawable/help_background_selector"
        android:id="@+id/workspace"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent">

        <LinearLayout android:id="@+id/dots_layout"
            android:layout_gravity="bottom|center_horizontal"
            android:layout_height="wrap_content"
            android:layout_marginbottom="28dip"
            android:layout_width="wrap_content"
            android:orientation="horizontal" />

    </com.ringcentral.android.utils.ui.widget.mygroup>
</FrameLayout>

指示點的形狀定義:

<shape android:shape="oval"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <size android:height="6dip" android:width="6dip" />
    <solid android:color="#7fffffff" />
</shape>

七、在 Activity 中組裝

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    final ViewGroup dotsLayout = (ViewGroup) findViewById(R.id.dots_layout);

    final int[] images = new int[]{
        R.drawable.help_01, R.drawable.help_02, R.drawable.help_03
    };

    final MyGroup myGroup = (MyGroup) findViewById(R.id.workspace);

    final Bundle dotsState = new Bundle();
    int margin = getResources().getDimensionPixelSize(R.dimen.workspace_dot_margin);
    dotsState.putInt(MyGroup.KEY_POINT_MARGIN, margin);
    MyGroup.updateDots(dotsLayout, images.length, 0, dotsState);

    for (int i = 0; i < 3; i++) {
        final View item = getLayoutInflater().inflate(R.layout.introduction_item_test, null);
        myGroup.addView(item);
        final ImageView imageView = (ImageView) item.findViewById(R.id.introduction_image_view);
        try {
            imageView.setImageResource(images[i]);
        } catch (OutOfMemoryError e) {
            // 圖片過大時保護
        }
    }

    myGroup.setmListener(new OnViewChangedListener() {
        @Override
        public void onViewChanged(int viewIndex) {
            myGroup.updateDots(dotsLayout, images.length, viewIndex, dotsState);
        }
    });

    myGroup.setSnapListener(new WorkspaceSnapListener() {
        @Override
        public void onSnapToScreen(MyGroup workspace, int whichScreen) {
            myGroup.updateDots(dotsLayout, images.length, whichScreen, dotsState);
        }
    });
}

效果圖:

仔細看這套實作,有兩個設計值得借鏡:一是用 INVISIBLE 而非 GONE 來隱藏非當前頁,因為 GONE 會讓子 View 不參與佈局,座標計算會出錯;二是把「頁面切換」與「滑動對齊」拆成兩個監聽器,前者在動畫結束後觸發、後者在對頁開始時觸發,這樣指示點的更新時機就能精準對應使用者的視覺感受。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved