1、MPAndroidChart柱状图——BarChart使用
(1)布局文件
<com.github.mikephil.charting.charts.BarChart
android:id="@+id/bc_sleep_quality"
android:layout_width="match_parent"
android:layout_height="200dp"
app:layout_constraintTop_toBottomOf="@id/tv_sleep_quality"
android:layout_marginHorizontal="16dp"
/>
(2)设置初始值
binding.bcSleepQuality.apply {
setDrawBarShadow(false)
animateY(1000) //Y轴动画时间
description.isEnabled = false
xAxis.apply {
position = XAxis.XAxisPosition.BOTTOM
labelCount = 7
textSize = 10f
setDrawGridLines(false)
axisMaximum = 8f
axisMinimum = 0f
xOffset = 1f
textColor = ContextCompat.getColor(mContext!!, R.color.overview_text_information)
this.valueFormatter = valueFormatter
}
axisLeft.apply {
textSize = 10f
gridColor = 0x00000000
axisMinimum = 0f
axisMaximum = 100f
textColor = ContextCompat.getColor(mContext!!, R.color.overview_text_information)
}
axisRight.apply {
isEnabled = false
axisMinimum = 0f
}
setTouchEnabled(false)
//设置是否可以缩放 x和y,默认true
setScaleEnabled(false)
//设置是否可以通过双击屏幕放大图表。默认是true
isDoubleTapToZoomEnabled = false
//图表背景颜色的设置
setBackgroundResource(R.drawable.bg_chart)
}
val valueFormatter = object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
//转化一下数据
return
}
}
(3)将数据转化成BarEntry->BarDataSet->BarData 一个套娃过程,最后把bardata设置到barchart的data属性中即可
private fun setSleepQualityToUI(list: MutableList<RoomSleepReport>) {
val temp = mutableListOf<BarEntry>()
for (roomSleepReport in list) {
temp.add(
BarEntry(
roomSleepReport.reportEndDay!!.toFloat(),
roomSleepReport.reportScore!!.toFloat()
)
)
}
val createBarData = createBarChartData(temp, false)
if (binding.bcSleepQuality.data != null && binding.bcSleepQuality.data.dataSetCount > 0) {
binding.bcSleepQuality.clearValues()
}
binding.bcSleepQuality.data = createBarData
binding.bcSleepQuality.data.notifyDataChanged()
binding.bcSleepQuality.notifyDataSetChanged()
}
private fun createBarChartData(temp: MutableList<BarEntry>, yellow: Boolean): BarData {
val barDataSet = BarDataSet(temp, "")
if (yellow) {
barDataSet.color =
ContextCompat.getColor(mContext!!, R.color.sleep_duration_barChart_color)
} else {
barDataSet.color =
ContextCompat.getColor(mContext!!, R.color.sleep_quality_barChart_color)
}
val dataSets = arrayListOf<IBarDataSet>()
dataSets.add(barDataSet)
val barData = BarData(dataSets)
barData.setValueTextSize(10f)
barData.setValueTextColor(
ContextCompat.getColor(
mContext!!,
R.color.overview_text_information
)
)
return barData
}
|