Search code examples
androidandroid-studioviewportandroid-graphviewlinegraph

Android Graph View auto scrollable Line Graph


I have created a line graph using Grap View and I am able to scroll it manually right and left but I am unable to set it to scroll automatically. So far I haven't found any thread in which someone would try this so I am wondering if Graph View even supports auto scroll.

This is my code so far:

    graph = (GraphView) findViewById(R.id.graph);

    // first series is a line
    DataPoint[] points = new DataPoint[1000];
    for (int i = 0; i < points.length; i++) {
        points[i] = new DataPoint(i, Math.sin(i*0.5) * 20*(Math.random()*10+1));
    }
    series = new LineGraphSeries<>(points);

    // set manual X bounds
    graph.getViewport().setYAxisBoundsManual(true);
    graph.getViewport().setMinY(-150);
    graph.getViewport().setMaxY(200);

    graph.getViewport().setXAxisBoundsManual(true);

    Handler handler1 = new Handler();
    for (orderNr = 1; orderNr < 50 ;orderNr++) {
        handler1.postDelayed(new Runnable() {

            @Override
            public void run() {
                graph.getViewport().setMinX(orderNr);
                graph.getViewport().setMaxX(orderNr + 100);
                graph.addSeries(series);

            }
        }, 1000);
    }
    graph.getViewport().setScrollable(true); // enables horizontal scrolling

If i do not do it within a Thread the lines

graph.getViewport().setMinX(orderNr) and
graph.getViewport().setMaxX(orderNr + 100)

set the graph to start and end at the specified spot but when they are put in a Thread I think that the Thread first finishes, reaching max orderNr and then draws out the graph.

Maybe someone has tried this with MPAndroidChart or aChartEngine or something else and can tell me what I am doing wrong here.


Solution

  • This problem also happened to me, but I got around it by setting isScalable to true and scroll to end at every update. This code results in a graphView that has a scrolling width of 30 and y limits at 0 and 1000.

    class ScrollingGraphView(context: Context, attrs: AttributeSet): GraphView(context, attrs) {
        private var series = LineGraphSeries<DataPoint>();
        private var x = 0.0
    
        init {
            addSeries(series)
            viewport.isScrollable = true
            viewport.isScalable = true
            viewport.isYAxisBoundsManual = true
            viewport.setMinY(0.0)
            viewport.setMaxY(1000.0)
            viewport.setMinX(0.0)
            viewport.setMaxX(30.0)
        }
    
        fun addEntry(y:Double?) {
            if(null != y) {
                x += .1
                series.appendData(DataPoint(x, y), true, 200)
            }
            invalidate()
            viewport.scrollToEnd()
        }