效果图
1. 添加依赖
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
}
2. XML界面
<com.github.mikephil.charting.charts.BarChart
android:id="@+id/bar_chart"
android:layout_width="match_parent"
android:layout_height="400dp"
/>
3. 实现代码
// 条状图
BarChart barChart = (BarChart)root.findViewById(R.id.bar_chart);
List<BarEntry> barEntryList = new ArrayList<>();
barEntryList.add(new BarEntry(1,11));
barEntryList.add(new BarEntry(2,36));
barEntryList.add(new BarEntry(3,23));
barEntryList.add(new BarEntry(4,15));
barEntryList.add(new BarEntry(5,12));
barEntryList.add(new BarEntry(6,15));
barEntryList.add(new BarEntry(7,110));
BarDataSet barDataSet = new BarDataSet(barEntryList, "");
// 设置颜色(7个柱子,7个颜色)
List<Integer> colors = new ArrayList<Integer>();
colors.add(getResources().getColor(R.color.context_title_bg));
colors.add(getResources().getColor(R.color.context_title_bg));
colors.add(getResources().getColor(R.color.context_title_bg));
colors.add(getResources().getColor(R.color.context_title_bg));
colors.add(getResources().getColor(R.color.context_title_bg));
colors.add(getResources().getColor(R.color.context_title_bg));
colors.add(getResources().getColor(R.color.context_title_bg));
barDataSet.setColors(colors);
BarData barData = new BarData(barDataSet);
barChart.setData(barData);
barData.setValueTextSize(10);
// 去除description
barChart.getDescription().setEnabled(false);
// 去除 Legend
barChart.getLegend().setEnabled(false);
// 去除对图标的触摸操作,如果没有去除,可以通过触摸对折线图进行
// 放大,缩小等操作。
barChart.setTouchEnabled(false);
// X轴处理
XAxis barXaxis = barChart.getXAxis();
// 设置X轴的位置为正下方
barXaxis.setPosition(XAxis.XAxisPosition.BOTTOM);
// 自定义X轴上的刻度显示
barXaxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return "12/" + (int) value;
}
});
// Y轴处理
YAxis barYaxis = barChart.getAxis(YAxis.AxisDependency.LEFT);
barYaxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return (int) value + "分";
}
});
// 隐藏右侧Y轴
barChart.getAxisRight().setEnabled(false);
注意的问题
几个柱子几个颜色。因为需要柱子都单色,所以七个颜色都设置成一样的。