问题
I am using the MPAndroidChart library in my Android graphs app and I need to display the dialog with a title containing the selected bar's x-axis values.
I referred to this wiki entry for click events to the bars in the bar graph. But now I need to get the selected bar x-axis value as a title. Can any one tell me how to achieve it?
回答1:
Use the OnChartValueSelectedListener
:
@Override
public void onValueSelected(Entry e, Highlight h) {
final String x = chart.getXAxis().getValueFormatter().getFormattedValue(e.getX(), chart.getXAxis());
}
The Highlight
object contains additional information regarding the selected position, such as the dataSetIndex, x- and y-position of the selected value in pixels, the selected stack value (in stacked bar chart), ...
Also hava a look at the documentation of highlighting values.
回答2:
Update: for MPAndroidChart 3.x.x the following works as per this answer:
chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
@Override
public void onValueSelected(Entry e, Highlight h) {
chart.getXAxis().getValueFormatter().getFormattedValue(e.getX(), chart.getXAxis());
}
@Override
public void onNothingSelected() {
}
});
回答3:
Use the onValueSelected:
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
int position = e.getXIndex();
Log.d("positin", position );
//XValue
final String selectedValue=barchart.getXAxis().getValues().get(position);
Log.d("selctdX", selectedValue);
//YValue
final String selectedYValue = String.valueOf(e.getVal());
Log.d("selctdY", selectedValue);
}
You can get position, xaxis value and yaxis value for selected bar using this code.
来源:https://stackoverflow.com/questions/34847411/how-to-get-selected-bar-x-axis-value-using-mpandroidchart