2013-05-30 37 views
1

我擴展了HorizontalScrollView類來實現某種行爲。在我的CustomHorizontalScrollView裏面的LinearLayout下,我只有兩個子視圖(可以說ImageView)。當用戶向一個方向滾動50%以上時,我希望我的CustomHorizontalScrollView自動滾動到同一方向的末尾。這是我是如何實現它:
CustomHorizontalScrollView類:Horizo​​ntalScrollView smoothScrolTo不起作用

public class CustomHorizontalScrollView extends HorizontalScrollView { 

    private static float downCoordinates = -1; 
    private static float upCoordinates = -1; 
    private static int currentPosition = 0; 

    public CustomHorizontalScrollView(Context ctx) { 
     super(ctx); 
    } 

    public CustomHorizontalScrollView(Context ctx, AttributeSet attrs) { 
     super(ctx, attrs); 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent ev) { 
     if (ev.getAction() == MotionEvent.ACTION_DOWN && downCoordinates == -1) { 
      downCoordinates = ev.getX(); 
     } 
     else if (ev.getAction() == MotionEvent.ACTION_UP && upCoordinates == -1) { 
      upCoordinates = ev.getX(); 
      int scrollViewWidth = this.getMeasuredWidth(); 
      double dist = downCoordinates - upCoordinates; 
      if (Math.abs(dist) > scrollViewWidth/2) { 
       //this.setSmoothScrollingEnabled(true); 
       // Going forwards 
       if (dist > 0) { 
        int max = ((LinearLayout)this.getChildAt(0)).getChildAt(1).getMeasuredWidth(); 
        currentPosition = max; 
        this.scrollTo(max, 0); 
       } 
       // Going backwards 
       else { 
        currentPosition = 0; 
        this.scrollTo(0, 0); 
       } 
      } 
      // reseting the saved Coordinates 
      downCoordinates = -1; 
      upCoordinates = -1; 
     } 
     return super.onTouchEvent(ev); 
    } 
} 

直到這裏 - 一切正常。問題是我想讓自動滾動順利完成,所以我嘗試使用smoothScrollTo函數而不是scrollTo函數,但之後沒有任何反應(如在沒有自動滾動的情況下)。我試過申明:

this.setSmoothScrollingEnabled(true); 

但也沒有成功。

回答

12

你試過嗎?

this.post(new Runnable() { 
     public void run() { 
      this.smoothScrollTo(0, this.getBottom()); 
     } 
}); 
+2

THX的作品!你能解釋我爲什麼需要這樣做嗎? –

1

這仍然不爲我工作,所以我發現,我需要這條線後

this.smoothScrollTo(0, this.getBottom()); 

添加此

this.invalidate(); 
相關問題