override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val chart = findViewById<PieChart>(R.id.chart)
val myData = listOf(10f,20f,50f)
// Step 1: Create a list of PieEntry objects that uses
// the source data index as its "data" attribute
val entries = myData.mapIndexed { i, v -> PieEntry(v, i)}
val dataset = PieDataSet(entries, "Values")
dataset.isHighlightEnabled = true
dataset.valueTextSize = 14f
dataset.colors = listOf(
Color.parseColor("#FF32DA64"),
Color.parseColor("#FF32DAD4"),
Color.parseColor("#FFB853F2")
)
// Step 2: Create a value formatter that compares the pie entry data
// (aka index in the original list) with the selected index to choose
// what value to show
val myValueFormatter = object : ValueFormatter() {
override fun getPieLabel(value: Float, pieEntry: PieEntry?): String {
val idx = pieEntry?.data as? Int ?: -2
return if (idx == selectedIndex ) {
// Show the value for the selected item
"$value"
}
else {
// Show percentage for all the rest
"${value / myData.sum() * 100f} %"
}
}
}
dataset.valueFormatter = myValueFormatter
// Step 3: Add a value selected listener to change the selected index
chart.setOnChartValueSelectedListener(object : OnChartValueSelectedListener {
override fun onValueSelected(e: Entry?, h: Highlight?) {
selectedIndex = h?.x?.roundToInt() ?: -1
}
override fun onNothingSelected() {
selectedIndex = -1
}
})
chart.data = PieData(dataset)
chart.description.isEnabled = false
chart.legend.isEnabled = false
}
1条答案
按热度按时间oknwwptz1#
为此,可以为每个
PieEntry
设置唯一的index属性,使用OnChartValueSelectedListener
跟踪选中的项,使用ValueFormatter
根据该项是否为选中项来选择如何呈现该项的值文本。如下所示(左侧取消选择,右侧选择):