我想在Android Studio
的图表视图中的数据点上添加点击侦听器。
我的java代码中存在一个问题:无法在最后一行代码中解析方法get Activity()
。
帮我解决问题。
这是我的代码:
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();
}
});
}
}
答案 0 :(得分:2)
您的OnDataPointTapListener
是一个匿名类,在此类中,方法getActivity
不存在,但它确实在您的Activity中退出。您应该使用this
中的MainActivity
而不是OnDataPointTapListener
中的Toast.makeText(MainActivity.this.getActivity(), "Series1: On Data Point clicked: "+dataPoint, Toast.LENGTH_SHORT).show();
:
{{1}}
答案 1 :(得分:1)
而不是将getActivity放入MainActivity.this
Toast.makeText(MainActivity.this, "Series1: On Data Point clicked: "+dataPoint, Toast.LENGTH_SHORT).show();