简体   繁体   中英

Drawing touch-interactive charts in Android

I need to use charts in Android and have unsuccessfully tried the various aChartEngine , AndroidPlot , and other libraries. I need the user to tap on an item and trap the event, those libraries do not handle this.

So I decided to build charts from scratch. I think to use canvas but I would like to know how can I get the touch event on a drawn item (if possible avoiding to get the touch coordinates and seeing if they intersect with an object, if I handle device rotation this can be difficult to handle).

Has anyone examples of canvas drawn images that can be touched?

It is easy. On a view you are using to draw you chart add a TouchListener and then check if the touched point is within your circle. In this example I'm checking if touched point is within rectangle around the pie chart:

this.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float x = event.getX();
                float y = event.getY();
                if (x < (centreX-r) || x> (centreX+r) || y <(centreY-r) || y>(centreY+r)) {
                    return false;
                }
                //do whatever you need to do
                return true;
            }
        });

Of course, if you need to know exactly which slice was pressed, you will have to add some logic to determine the slice based on the point and angle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM