2013-07-25 262 views
0

我有課,它以垂直方式畫很多十字架。我想學習如何做到這一點,所以我試試這個簡單的例子:Android垂直滾動

public class Draw extends View { 
    Paint paint = new Paint(); 

    public Draw(Context context) { 
     super(context); 
     paint.setColor(Color.BLACK); 
    } 

    @Override 
    public void onDraw(Canvas canvas) { 
     int x = 1; 
     for(int i = 0; i < 100; i++){ 

    if (i%2 == 0) x = 2; 
    else x=1; 
      canvas.drawLine(0, 0 + x*i*20, 20, 20 + x*i*20, paint); 
      canvas.drawLine(20, 0 + x*i*20, 0, 20 + x*i*20, paint); 
     } 
    } 

}

,我想滾動它。

我實現的onTouchEvent與MotionEvent.ACTION_MOVE:

public class DrawActivity extends Activity { 

    private Draw dv; 
    private float xDistance, yDistance, lastX, lastY; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     dv = new Draw(this); 
     setContentView(dv); 

    } 

    public boolean onTouchEvent(MotionEvent event) { 

     int action = MotionEventCompat.getActionMasked(event); 

     switch (action) { 

     case (MotionEvent.ACTION_MOVE): 
      final float curX = event.getX(); 
      final float curY = event.getY(); 
      xDistance += Math.abs(curX - lastX); 
      yDistance += Math.abs(curY - lastY); 
      lastX = curX; 
      lastY = curY; 
      if (xDistance > yDistance) 
       return false; 

     default: 
      return super.onTouchEvent(event); 

     } 
    } 

} 

,但它不能正常工作。我如何滾動畫布?

回答

0

由於您正在擴展視圖,因此應更新它的scrollX值(或存儲自身)並將其內容轉換爲其值。