首先下载依赖库 ,有现成的jar包:hellocharts-library-1.5.8.jar
在需要的布局中直接使用:
<lecho.lib.hellocharts.view.ColumnChartView android:id="@+id/columnchart" android:layout_width="match_parent" android:layout_height="match_parent" />
例如绘制一年的数据:
伪代码:
//声明所需变量
public final static String[] months = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; ColumnChartView columnChart; ColumnChartData columnData; List<Column> lsColumn = new ArrayList<Column>(); List<SubcolumnValue> lsValue;
//初始化数据并显示在图表上
private void dataInit() {
int numSubcolumns = 1;
int numColumns = months.length;
List<AxisValue> axisValues = new ArrayList<AxisValue>();
List<Column> columns = new ArrayList<Column>();
List<SubcolumnValue> values;
for (int i = 0; i < numColumns; ++i) {
values = new ArrayList<SubcolumnValue>();
for (int j = 0; j < numSubcolumns; ++j) {
values.add(new SubcolumnValue((float) Math.random() * 50f + 5,
ChartUtils.pickColor()));
}
// 点击柱状图就展示数据量
axisValues.add(new AxisValue(i).setLabel(months[i]));
columns.add(new Column(values).setHasLabelsOnlyForSelected(true));
}
columnData = new ColumnChartData(columns);
columnData.setAxisXBottom(new Axis(axisValues).setHasLines(true)
.setTextColor(Color.BLACK));
columnData.setAxisYLeft(new Axis().setHasLines(true)
.setTextColor(Color.BLACK).setMaxLabelChars(2));
columnChart.setColumnChartData(columnData);
// Set value touch listener that will trigger changes for chartTop.
columnChart.setOnValueTouchListener(new ValueTouchListener());
// Set selection mode to keep selected month column highlighted.
columnChart.setValueSelectionEnabled(true);
columnChart.setZoomType(ZoomType.HORIZONTAL);
}
/**
* 柱状图监听器
*
* @author 1017
*
*/
private class ValueTouchListener implements
ColumnChartOnValueSelectListener {
@Override
public void onValueSelected(int columnIndex, int subcolumnIndex,
SubcolumnValue value) {
// generateLineData(value.getColor(), 100);
}
@Override
public void onValueDeselected() {
// generateLineData(ChartUtils.COLOR_GREEN, 0);
}
}
最后出来的效果:
点击对应的柱状图就会显示当前项的数据;