How to get selected bar x-axis value using MPAndroidChart?

烈酒焚心 提交于 2020-01-11 09:21:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!