Android 視圖切換效果
我們先來看看效果圖:
上述截圖,是手指拖動的效果,如果拖動過屏幕中點,鬆手後就會自動移動到第二屏。另外,如果使用輕掃手勢,也可以自動移動下一屏。
Android中的View有兩個子類,Widget和ViewGroup,Widget是可見的窗口組件,比如按鈕,ViewGroup就是布局,ViewGroup已經提供了多個布局子類,比如LinearLayout等。
本例中實現了自己的ViewGroup子類。通過覆蓋onLayout方法實現對子視圖的橫向排列布局:
Java代碼:
- package eoe. result;
- @Override
- protected void onLayout(boolean changed, int left, int top, int right,
- int bottom) {
- Log.d(TAG, ">>left: " + left + " top: " + top + " right: " + right
- + " bottom:" + bottom);
- /**
- * 設置布局,將子視圖順序橫屏排列
- */
- for (int i = 0; i < getChildCount(); i++) {
- View child = getChildAt(i);
- child.setVisibility(View.VISIBLE);
- child.measure(right – left, bottom – top);
- child.layout(0 + i * getWidth(), 0, getWidth() + i * getWidth(),
- getHeight());
通過覆蓋computeScroll方法,計算移動屏幕的位移和重新繪製屏幕:
Java代碼:
- package eoe. result;
- @Override
- public void computeScroll() {
- if (scroller.computeScrollOffset()) {
- scrollTo(scroller.getCurrX(), 0);
- postInvalidate();
- }
- }
編寫了一個名為scrollToScreen的方法,用於根據指定屏幕號切換到該屏幕:
Java代碼:
- /**
- * 切換到指定屏
- *
- * @param whichScreen
- */
- public void scrollToScreen(int whichScreen) {
- if (getFocusedChild() != null && whichScreen != currentScreenIndex
- && getFocusedChild() == getChildAt(currentScreenIndex)) {
- getFocusedChild().clearFocus();
- }
- final int delta = whichScreen * getWidth() – getScrollX();
- scroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);
- invalidate();
- currentScreenIndex = whichScreen;
- }
snapToDestination方法,是處理當屏幕拖動到一個位置鬆手後的處理:
Java代碼:
- /**
- * 根據當前x坐標位置確定切換到第幾屏
- */
- private void snapToDestination() {
- scrollToScreen((getScrollX() + (getWidth() / 2)) / getWidth());
- }
然後說說手勢事件的處理。eric的實現,全部使用onTouch事件處理,這樣代碼不夠簡明。因為需要記錄很多組合手勢的曆史數據,這樣就必須有一些狀態位,一些坐標數值。
我用GestureDetector的手勢處理事件簡化了這方麵的處理,隻在手勢抬起(UP)事件處理中在ouTouchEvent方法中做了處理。
最後更新:2017-04-02 06:51:48