首先引入MPAndroidChart控件
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
在需要控件的页面布局上加上
<com.github.mikephil.charting.charts.BarChart
android:id="@+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="@dimen/dimens_120dp"
android:layout_marginRight="@dimen/dimens_120dp" />
简单封装一下以便添加数据(按需求封装),并设置样式,代码使用kotlin
/**
* 设置数据
*/
fun setData(xValues: List<String>, ydata: List<String>) {
try {
chart.setDrawBarShadow(false)
chart.setNoDataText("暂无统计数据")//设置无数据时显示文字
chart.legend.verticalAlignment = Legend.LegendVerticalAlignment.CENTER
chart.legend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
chart.legend.orientation = Legend.LegendOrientation.VERTICAL
chart.legend.formSize = 18f
chart.legend.textSize = 16f
chart.legend.formToTextSpace = 5f
//条形图颜色
var colors = arrayListOf<Int>()
colors.add(Color.parseColor("#FE787A"))
colors.add(Color.parseColor("#FFD179"))
colors.add(Color.parseColor("#60B8F6"))
colors.add(Color.parseColor("#92ECA3"))
colors.add(Color.parseColor("#9287e7"))
colors.add(Color.parseColor("#32d3eb"))
colors.add(Color.parseColor("#5bc49f"))
//y轴数据
var yValues = arrayListOf<BarEntry>()
for (i in 0 until ydata.size) {
yValues.add(BarEntry(i.toFloat(), ydata[i].toFloat()))
}
var dataSet = BarDataSet(yValues, "")
//设置柱状图顶部的值
dataSet.setValueFormatter { value, _, _, _ -> value.toInt().toString() + "人" }
dataSet.colors = colors
var data = BarData(dataSet)
chart.setDrawBorders(false)
chart.setTouchEnabled(false)
chart.isDragEnabled = false// 是否可以拖拽
chart.setScaleEnabled(false)//是否可放大
chart.setDrawGridBackground(false)//是否绘制网格线
chart.axisRight.isEnabled = false
chart.description.isEnabled = false
chart.xAxis.setValueFormatter { value, axis ->
xValues[value.toInt()]
}
chart.xAxis.position = XAxis.XAxisPosition.BOTTOM
chart.xAxis.setDrawGridLines(false)
chart.axisLeft.setDrawGridLines(false)
chart.legend.isEnabled = true
chart.legend.xEntrySpace = 5f
chart.legend.yEntrySpace = 5f
chart.legend.stackSpace = 5f
chart.legend.xOffset = 5f
chart.xAxis.setLabelCount(xValues.size, false)
chart.axisLeft.setValueFormatter { value, axis ->
value.toInt().toString() + "人"
}
//设置标签
var legends = arrayListOf<LegendEntry>()
for (i in 0 until xValues.size) {
var legendEntry = LegendEntry()
legendEntry.formColor = colors[i]
legendEntry.label = xValues[i] + ": " + yValues[i].y.toInt() + "人"
legends.add(legendEntry)
}
//保证Y轴从0开始,不然会上移一点
chart.axisLeft.axisMinimum = 0f
//设置自增长的值
chart.axisLeft.granularity = 1f
//设置标签
chart.legend.setCustom(legends)
var count = 0
ydata.forEach {
count += it.toInt()
}
//设置数据
if (ydata != null && ydata.isNotEmpty() && count > 0)
chart.data = data
//设置柱状图宽度(绑定数据后设置有效)
chart.setVisibleXRange(5f, 10f)
chart.invalidate()
} catch (e: Exception) {
e.printStackTrace()
}
}
最终实现效果