android graphview获取触摸位置

时间:2013-01-22 06:03:41

标签: android touch-event

首先,我在我的应用http://www.jjoe64.com/p/graphview-library.html中使用此库来创建图表。然后,我使用此代码(我在评论中找到)来获取触摸事件的x位置。

//intercepts touch events on the graphview
@Override
public boolean dispatchTouchEvent(MotionEvent event) { 
    switch (event.getAction()) {
        //when you touch the screen
        case MotionEvent.ACTION_DOWN:
            // gets the location of the touch on the graphview
            float x = event.getX(event.getActionIndex());
            // gets the boundries of what you are viewing from the function you just added
//  vp is set to vp[0] = 0 & vp[1] = numDaysOil, numDaysOil could be anywhere from 2 to 30 
            double[] vp = graphOilView.getViewPort();
            // gets the width of the graphview
            int width = graphOilView.getWidth();
             //gets the x-Value of the graph where you touched
            @SuppressWarnings("unused")
            double xValue = vp[0] + (x / width) * vp[1];
// trying a different ways to get different x vaules 
            double xVal = (x / width) * numDaysOil;
            //add a method to lookup a value and do anything you want based on xValue. 

            break;
        } // end switch
    return super.dispatchTouchEvent(event);
} // end dispatchTouch Event

取决于您触摸的位置(或单击模拟器),我将得到正确的x值,但有时会得到x值的小或大。

谁对此有任何见解?

编辑:有时当我点击图表中的某个位置时,xValue将返回正确的x值,有时会返回一个小于或大于与y值对应的x值的xValue。示例用于在图上创建点的x值为12,y值为30,但使用上面的代码计算的xValue可能返回9.因此,如果我然后尝试查找x = 9,我将得到错误的y值。绘制的数据:x:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 y:5,16,8,11,1,30,20 ,11,18,29,27,30,8,10,19

1 个答案:

答案 0 :(得分:0)

我解决了这个问题:

graphView = new LineGraphView(context,"Title");
graphView = initGraphView(graphView);    
graphView.setOnTouchListener(new OnTouchListener(){
                public boolean onTouch(View v, MotionEvent event) {
                    if(event.getAction() == MotionEvent.ACTION_DOWN) {
                        int size = series1.size();
                        float screenX = event.getX();
                        float screenY = event.getY();
                        float width_x = v.getWidth();
                        float viewX = screenX - v.getLeft();
                        float viewY = screenY - v.getTop();
                        float percent_x = (viewX/width_x);
                        int pos = (int) (size*percent_x);

                        System.out.println("X: " + viewX + " Y: " + viewY +" Percent = " +percent_x);
                        System.out.println("YVal = " +series1.getY(pos));
                        tvNum.setText(series1.getY(pos)+"");
                        return true;
                    }
                    return false;
                }

            });

看起来与您的情况大致相同,但只要您想从视图中获取数字,请务必设置graphView.setScrollable(false)graphView.setScalable(false)。我认为这是包的一些奇怪的怪癖。我最终不得不停止数据收集并冻结'图表是为了从系列中获取x和y值。

有没有人知道更好的方法?