閱讀286 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Android 視圖切換效果

 我們先來看看效果圖:
8.png 

       上述截圖,是手指拖動的效果,如果拖動過屏幕中點,鬆手後就會自動移動到第二屏。另外,如果使用輕掃手勢,也可以自動移動下一屏。

        Android中的View有兩個子類,WidgetViewGroupWidget是可見的窗口組件,比如按鈕,ViewGroup就是布局,ViewGroup已經提供了多個布局子類,比如LinearLayout等。

       本例中實現了自己的ViewGroup子類。通過覆蓋onLayout方法實現對子視圖的橫向排列布局:

Java代碼:

  1. package eoe. result;

  2. @Override
  3. protected void onLayout(boolean changed, int left, int top, int right,
  4. int bottom) {
  5. Log.d(TAG, ">>left: " + left + " top: " + top + " right: " + right
  6. + " bottom:" + bottom);

  7. /**
  8. * 設置布局,將子視圖順序橫屏排列
  9. */
  10. for (int i = 0; i < getChildCount(); i++) {
  11. View child = getChildAt(i);
  12. child.setVisibility(View.VISIBLE);
  13. child.measure(right – left, bottom – top);
  14. child.layout(0 + i * getWidth(), 0, getWidth() + i * getWidth(),
  15. getHeight());
複製代碼

        通過覆蓋computeScroll方法,計算移動屏幕的位移和重新繪製屏幕:

Java代碼:
  1. package eoe. result;

  2. @Override
  3. public void computeScroll() {
  4. if (scroller.computeScrollOffset()) {
  5. scrollTo(scroller.getCurrX(), 0);
  6. postInvalidate();
  7. }
  8. }
複製代碼

        編寫了一個名為scrollToScreen的方法,用於根據指定屏幕號切換到該屏幕:

Java代碼:
  1. /**
  2. * 切換到指定屏
  3. *
  4. * @param whichScreen
  5. */
  6. public void scrollToScreen(int whichScreen) {
  7. if (getFocusedChild() != null && whichScreen != currentScreenIndex
  8. && getFocusedChild() == getChildAt(currentScreenIndex)) {
  9. getFocusedChild().clearFocus();
  10. }

  11. final int delta = whichScreen * getWidth() – getScrollX();
  12. scroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);
  13. invalidate();

  14. currentScreenIndex = whichScreen;
  15. }
複製代碼

        snapToDestination方法,是處理當屏幕拖動到一個位置鬆手後的處理:

Java代碼:
  1. /**
  2. * 根據當前x坐標位置確定切換到第幾屏
  3. */
  4. private void snapToDestination() {
  5. scrollToScreen((getScrollX() + (getWidth() / 2)) / getWidth());
  6. }
複製代碼

       然後說說手勢事件的處理。eric的實現,全部使用onTouch事件處理,這樣代碼不夠簡明。因為需要記錄很多組合手勢的曆史數據,這樣就必須有一些狀態位,一些坐標數值。

       我用GestureDetector的手勢處理事件簡化了這方麵的處理,隻在手勢抬起(UP)事件處理中在ouTouchEvent方法中做了處理。

最後更新:2017-04-02 06:51:48

  上一篇:go android多任務同時下載
  下一篇:go 【usaco】 checker