AFreeChart -最低限のグラフを描く
1.グラフのViewを準備するクラス
public class GraphView extends View {
private AFreeChart chart;
private RectShape chartArea;
public GraphView(Context context, AttributeSet attrs) {
super(context, attrs);
chartArea = new RectShape();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
chartArea.setWidth(w);
// chartArea.setHeight(h / 2);
chartArea.setHeight(h);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.chart.draw(canvas, chartArea);
}
public void setChart(AFreeChart chart) {
this.chart = chart;
}
}
2.時系列グラフを描くクラス
public class SampleChart {
public void createChart(View view) {
TimeSeries series = new TimeSeries("時系列データ");
series.add(new Month(7, 2007), 120);
series.add(new Month(8, 2007), 140);
series.add(new Month(9, 2007), 150);
series.add(new Month(10, 2007), 190);
series.add(new Month(11, 2007), 230);
series.add(new Month(12, 2007), 280);
TimeSeriesCollection data = new TimeSeriesCollection(series);
AFreeChart chart =
ChartFactory.createTimeSeriesChart("PV推移",
"月",
"PV",
data,
false, // ← 凡例無し
false,
false);
GraphView graphView = (GraphView) view;
graphView.setChart(chart);
}
}
3.レイアウト.xml
<com.jimdo.uchida001tmhr.graph.GraphView
android:id="@+id/sample_chart"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
4.MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
View view = findViewById(R.id.sample_chart);
SampleChart sampleChart = new SampleChart();
sampleChart.createChart(view);
}
(中略)
}
ここで、findViewById()をcreateChart()の中に入れてしまうと、NullPointerExceptionになってしまう。