本文介绍了MPAndroidChart:getColors()现在已不推荐使用“传奇".我应该怎么用呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在MPAndroidChart中显示PieChart的自定义图例,但是.getColors()和.getLabels()现在已弃用.

I'm displaying a custom legend for a PieChart in MPAndroidChart however, .getColors() and .getLabels() are now deprecated.

我一直在使用它们分别获取一个int数组和一个字符串数组,但是我似乎找不到直接的替代方法.我缺少明显的东西吗?我现在应该使用什么呢?谢谢!

I've been using them to get an int array and string array respectively but I can't seem to find a direct alternative. Am I missing something obvious? What should I now use instead? Thanks!

Legend legend = mChart.getLegend();
legend.setEnabled(false);

if (legend.getColors() != null) {

    int colorCodes[] = legend.getColors();
    String labels[] = legend.getLabels();

    ArrayList<LegendItem> legendItems = new ArrayList<>();

    for (int i = 0; i < legend.getColors().length-1; i++) {
        legendItems.add(new LegendItem(colorCodes[i], labels[i]));
    }

    showLegend(legendItems);

    // entry label styling
    mChart.setDrawEntryLabels(false);

}

推荐答案

Legend类现在遵循更好的OOP实践,并且由LegendEntry数组组成.您可以遍历每种颜色,并根据需要提取颜色或标签.

The Legend class now follows better OOP practices and is composed of an array of LegendEntry. You can iterate through each and extract the colors or the labels as you wish.

private int [] getColors(Legend legend) {
    LegendEntry [] legendEntries = legend.getEntries();
    int [] colors = new int[legendEntries.length];
    for (int i = 0; i < legendEntries.length; i++) {
        colors[i] = legendEntries[i].formColor;
    }
    return colors;
}

private String [] getLabels(Legend legend) {
    LegendEntry [] legendEntries = legend.getEntries();
    String [] labels = new String[legendEntries.length];
    for (int i = 0; i < legendEntries.length; i++) {
        labels[i] = legendEntries[i].label;
    }
    return labels;
}

这篇关于MPAndroidChart:getColors()现在已不推荐使用“传奇".我应该怎么用呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 17:49