使用onValueSelected -MPEandroidChart显示的更改值

jvidinwx  于 2022-12-21  发布在  Android
关注(0)|答案(1)|浏览(98)

我在pieChart中显示百分比值。我想在用户单击切片时将这些值更改为真实的金额。可以使用onValueSelected()吗?我不想使用IMarker,因为它对我来说有点复杂。我尝试过这样做,但没有成功:

override fun onValueSelected(e: Entry?, h: Highlight?) {
    val amount = (e as PieEntry).value
    e.y = amount 
}
oknwwptz

oknwwptz1#

为此,可以为每个PieEntry设置唯一的index属性,使用OnChartValueSelectedListener跟踪选中的项,使用ValueFormatter根据该项是否为选中项来选择如何呈现该项的值文本。

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
}

如下所示(左侧取消选择,右侧选择):

相关问题