How to get selected bar x-axis name(Strings added to x-axis) using MP Chart?

一世执手 提交于 2019-12-24 08:23:12

问题


I know this is a duplicate to the linkquestion

I have followed the same but I am getting the following error :

 @Override
    public void onValueSelected(Entry e, Highlight h) {

    String xAxisValue = mChart.getData().getXVals().get(e.getXIndex());

}

ERROR : cannot resolve getXVals() and cannot resolve getXIndex()

Please help : I have the following x-axis values : India, Australia,US,China

On click of a Bar in barchart I need to get One of the above string


回答1:


In MPAndroidChart 3.0.0+ this should work:

chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
    @Override
    public void onValueSelected(Entry e, Highlight h) {
        chart.getXAxis().getValueFormatter().getFormattedValue(e.getX(), chart.getXAxis());
    }

    @Override
    public void onNothingSelected() {

    }
});



回答2:


If you are using your model class for drawing chart and when you click on bar, wants to get more values instead of just Y axis points or x axis name then below is the solution.

first Your activity or fragment should implements OnChartValueSelectedListener. then implement onValueSelected()

@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {


    String xAxisValue = chart.getData().getXVals().get(e.getXIndex());
    //yourList (model class or  pojo class type), first get the full list
    for (int i=0; i<yourList.size(); i++){
        YourModelClass cym = yourList.get(i);
        String year =cym.getYear();
        // compare the xAxisValue with one of your Model class attribute. which is written on x-axis of the graph
        if (year.equals(xAxisValue)){
            // now you got the index number of your list which is matched with xAxis Bar value. 
            //so do your stuff here. Something like setting text or showing toast etc etc
           // if done everything then break the loop
            break;
        }

    }

}

@Override
public void onNothingSelected() {
}


来源:https://stackoverflow.com/questions/41216241/how-to-get-selected-bar-x-axis-namestrings-added-to-x-axis-using-mp-chart

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