How to use onScroll for View in Android

时间:2015-10-06 08:45:17

标签: android gesture gesturedetector

I want to use the onScroll method of GestureDetector.SimpleOnGestureListener.

So far I have this code:

public class TouchView extends View {
private Drawable image;
private float scaleFactor = 1.0f;
private ScaleGestureDetector scaleGestureDetector;
private GestureDetector simpleOnGestureListener;
private FrameLayout root;

public TouchView(Context context) {
    super(context);
    image = context.getResources().getDrawable(R.drawable.wifi);
    setFocusable(true);
    image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
    scaleGestureDetector = new ScaleGestureDetector(context, new ScaleListener());
    simpleOnGestureListener = new GestureDetector(context,new MyGestureListener());
}


@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    canvas.scale(scaleFactor, scaleFactor);
    image.draw(canvas);
    canvas.restore();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    scaleGestureDetector.onTouchEvent(event);
    simpleOnGestureListener.onTouchEvent(event);
    invalidate();
    return true;
}


private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
    private static final String DEBUG_TAG = "Gestures";

    @Override
    public boolean onDown(MotionEvent event) {
        Log.d(DEBUG_TAG,"onDown: " + event.toString());
        return true;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2,float distanceX, float distanceY){

        return true;
    }
}

I want to make the View scrollable/draggable. So if I have two images drawn in the View and scroll, both drawings have to be scrolled.

I hope it's clear what I want to do!

Kind Regards!

1 个答案:

答案 0 :(得分:0)

只需将顶级布局设为ScrollView:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

  .......
  Your code            
  .......

</ScrollView>