Search code examples
androidandroid-graphview

How to listen for touch events on GraphView?


I need to add behavior to my program related to the user panning / zooming the GraphView. I am attempting to register for motion events to be notified of this, so I can do something as the user is manipulating the graph via touch.

I have tried overriding onTouchEvent and implementing OnTouchLIstener in a subclass of LineGraph. I have also tried doing this in the Fragment / View in which I am putting the GraphView. However, my methods are never called, but the graph allows for panning / zooming as before.

e.g.:

public CustomLineGraphView(Context context, String title) {
    super(context, title);
    this.setOnTouchListener(this);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    Log.w("clg", "onTouchEvent()");
    return true;
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    Log.w("clg", "onTouch()");
    return false;
}

Solution

  • You need to hook in to an underlying View that GraphView uses.

    Assuming you have a GraphView object built named m_graphView, do the following. It's probably safest to attach the onTouchListener to every underlying child, incase the implementation of GraphView changes down the road.

    // attach OnTouchListener to the inner view that receives touch events for pan/zoom.
    int childCount = m_graphView.getChildCount();
    for(int index = 0; index < childCount; index++) {
       m_graphView.getChildAt(index).setOnTouchListener(new GraphTouchListener());
    }
    

    Be sure to return false in onTouch() so the baseclass behavior of pan/zoom still works.

    private class GraphTouchListener implements View.OnTouchListener {
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // do whatever custom behavior you want here
            // return false so that the base onTouch event (pan, zoom) can still execute.
            return false;
        }
    }