October 21, 2024
Chicago 12, Melborne City, USA
Android

MPAndroidChart BarChart: Touch Events Not Working Due to Unsorted X-Axis Data


I’m using MPAndroidChart’s BarChart to visualize data in my Android app. The chart renders perfectly, but I’ve encountered an issue where touch events on the bars are not consistently recognized. Specifically, calling getHighlightByTouchPoint(event.x, event.y) almost always returns null, except for one specific bar.

Initial Data Handling:

I was constructing the BarChart using entries created from a Map<X, Y>:

val entries = mutableListOf<BarEntry>()
for ((timeIndex, list) in data) {
    val sum = list.sumOf { it.totalTime }.toFloat()
    entries.add(BarEntry(timeIndex.toFloat(), sum))
}

The chart would display correctly, but the click interactions were unreliable.

Problem:

When tapping on a bar, I expected the getHighlightByTouchPoint(x, y) method to return a valid highlight for the clicked bar.
However: Most taps would return null, except for one specific bar (seemingly random).
I verified that the bars were drawn at the correct coordinates programmatically, but despite this, tapping on those coordinates would still result in null highlights.
Additionally, the OnChartValueSelectedListener was always triggering the onNothingSelected() method, even when a bar was visually selected.

Investigation:

After further debugging, I realized that the X-axis values in my dataset were not sorted. Although the chart rendered the data as expected, the touch handling system relies on sorted X values for correct hit detection.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video