How do I get an onClickListener
for the xAxis labels? If this is not possible, is there any other way to receive click events on the xAxis labels?
The xAxis labels are not actually instances of View
. Instead, they are rendered directly onto the canvas by MPAndroidChart. So you can't have a OnClickListener
for them.
The way to do what you want, instead, is to implement a custom OnChartGestureListener
. The javadoc for that class is here
mChart.setOnChartGestureListener(new MyChartGestureListener());
In your MyChartGestureListener
you would override onChartSingleTapped(MotionEvent me)
:
@Override
public void onChartSingleTapped(MotionEvent me) {
float tappedX = me.getX();
float tappedY = me.getY();
MPPointD point = mChart.getTransformer(YAxis.AxisDependency.LEFT).getValuesByTouchPoint(tappedX, tappedY);
Log.d(TAG, "tapped at: " + point.x + "," + point.y);
}
The snippet above shows how to get the x and y values from the MotionEvent
. You would then need some logic to check if you are single tapping a label and not another part of the chart. Perhaps a conditional like:
if ((point.y) < labelYValue) {
Log.d(TAG, "tapped on label for x-value: " + point.x);
}
Or you could probably use the raw y
from the MotionEvent
if you prefer.