How to add tap listener on data point?

1.2k views Asked by At

I want to a add tap listener on a data point in the graph view in Android Studio.

There is a problem in my java code that says: can't resolve method get Activity() in last line of codes.

Help me resolve my problem.

Here is my code:

package com.example.graph;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.DataPointInterface;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.OnDataPointTapListener;
import com.jjoe64.graphview.series.PointsGraphSeries;
import com.jjoe64.graphview.series.Series;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GraphView graph = (GraphView) findViewById(R.id.graph);
        LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[] {
            new DataPoint(0, -2),
            new DataPoint(1, 5),
            new DataPoint(2, 3),
            new DataPoint(3, 2),
            new DataPoint(4, 6)
        });
        graph.addSeries(series);
        graph.setBackgroundColor(getResources().getColor(R.color.background_color));
        series.setThickness(5);
        graph.getViewport().setScalable(true);
        graph.getViewport().setScrollable(true);

        PointsGraphSeries<DataPoint> series2 = new PointsGraphSeries<>(new DataPoint[] {
            new DataPoint(0, -2),
            new DataPoint(1, 5),
            new DataPoint(2, 3),
            new DataPoint(3, 2),
            new DataPoint(4, 6)
        });
        graph.addSeries(series2);
        series2.setColor(Color.RED);
        series2.setSize(10);
        series2.setOnDataPointTapListener(new OnDataPointTapListener() {
            @Override
            public void onTap(Series series2, DataPointInterface dataPoint) {
                Toast.makeText(getActivity(), "Series1: On Data Point clicked: "+dataPoint, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
2

There are 2 answers

1
Rolf ツ On BEST ANSWER

Your OnDataPointTapListener is an anonymous class, inside this class the method getActivity does not exist, but it does exits within your Activity. You should use the this from your MainActivity not this from your OnDataPointTapListener:

Toast.makeText(MainActivity.this.getActivity(), "Series1: On Data Point clicked: "+dataPoint, Toast.LENGTH_SHORT).show();
1
garima On

Instead of getActivity put MainActivity.this

Toast.makeText(MainActivity.this, "Series1: On Data Point clicked: "+dataPoint, Toast.LENGTH_SHORT).show();