установить метку в barchart версии 3 MPAndroid - PullRequest
0 голосов
/ 13 сентября 2018

Я использую диаграмму из MPAndroidChart версии 3.

Я для набора меток использовал этот код:

public class MainActivity extends AppCompatActivity {

BarChart chart;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    chart =  (BarChart) findViewById(R.id.chart);

    List<BarEntry> entries = new ArrayList<>();
    entries.add(new BarEntry(0, 2000));
    entries.add(new BarEntry(1, 100));
    entries.add(new BarEntry(2, 500));
    entries.add(new BarEntry(3, 250));
    entries.add(new BarEntry(4, 170));
    entries.add(new BarEntry(5, 600));

    BarDataSet set = new BarDataSet(entries, "Recovery");

    BarData data = new BarData(set);
    data.setBarWidth(1);
    chart.setData(data);
    chart.setFitBars(true);
    chart.invalidate();

   String[] day = new String[]{"day1","day2","day3","day4","day5","day6"};
   XAxis xAxis = chart.getXAxis();
   xAxis.setValueFormatter(new LabelFormatter(day));
   xAxis.setGranularity(1);
}

public class LabelFormatter implements IAxisValueFormatter {
    private final String[] mLabels;

    public LabelFormatter(String[] labels) {
        mLabels = labels;
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return mLabels[(int) value];
    }
  }

но, к сожалению, я получаю эту ошибку:

java.lang.ArrayIndexOutOfBoundsException: length=6; index=-1

И этот раздел относится к этому коду:

 return mLabels[(int) value];

Я не знаю, что делать.

Как решить эту проблему ?!Спасибо.

Ответы [ 2 ]

0 голосов
/ 13 сентября 2018

Используйте эту функцию -

 public void create_graph(List<String> graph_label, List<Integer> userScore) {

    try {
        chart.setDrawBarShadow(false);
        chart.setDrawValueAboveBar(true);
        chart.getDescription().setEnabled(false);
        chart.setPinchZoom(false);

        chart.setDrawGridBackground(false);


        YAxis yAxis = chart.getAxisLeft();
        yAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value);
            }
        });

        yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);


        yAxis.setGranularity(1f);
        yAxis.setGranularityEnabled(true);

        chart.getAxisRight().setEnabled(false);


        XAxis xAxis = chart.getXAxis();
        xAxis.setGranularity(1f);
        xAxis.setGranularityEnabled(true);
        xAxis.setCenterAxisLabels(true);
        xAxis.setDrawGridLines(true);

        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new IndexAxisValueFormatter(graph_label));

        List<BarEntry> yVals1 = new ArrayList<BarEntry>();

        for (int i = 0; i < userScore.size(); i++) {
            yVals1.add(new BarEntry(i, userScore.get(i)));
        }


        BarDataSet set1;

        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create 2 datasets with different types
            set1 = new BarDataSet(yVals1, "SCORE");
            set1.setColor(Color.rgb(255, 204, 0));


            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            chart.setData(data);


        }

        chart.setFitBars(true);

        Legend l = chart.getLegend();
        l.setFormSize(12f); // set the size of the legend forms/shapes
        l.setForm(Legend.LegendForm.SQUARE); // set what type of form/shape should be used

        l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART_INSIDE);
        l.setTextSize(10f);
        l.setTextColor(Color.BLACK);
        l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
        l.setYEntrySpace(5f); // set the space between the legend entries on the y-axis

        chart.invalidate();

        chart.animateY(2000);

    } catch (Exception ignored) {
    }
}

И вызовите ее в Activity

 BarChart chart;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    chart = (BarChart) findViewById(R.id.barchart);
    List<Integer> entries = new ArrayList<>();
    entries.add(2000);
    entries.add(100);
    entries.add(500);
    entries.add(250);
    entries.add(170);
    entries.add(600);

    List<String> labels = new ArrayList<>();

    labels.add("day1");
    labels.add("day2");
    labels.add("day3");
    labels.add("day4");
    labels.add("day5");
    labels.add("day6");

    create_graph(labels,entries);
}
0 голосов
/ 13 сентября 2018

Кажется, что оно уже получает значение до того, как установлено mLabels. Вы можете установить его прямо на xAxis, и вам не нужно создавать LabelFormatter вроде:

xAxis.setValueFormatter(new IAxisValueFormatter() {
   @Override
   public String getFormattedValue(float value, AxisBase axis) {
        if (value >= 0) {
            if (day.length > (int) value) {
                return day[(int) value];
            } else { 
               return "";
            } 
        } else {
            return "";
        }
   }
});
...