MPAndroidChart - 饼图的所有部分都是相同的颜色

MPAndroidChart - all pieces of the pie chart are the same colour

我正在使用 MPAndroidChart (https://github.com/PhilJay/MPAndroidChart) 库生成饼图。我遵循了多个教程,包括维基页面,但是当我创建我的饼图时,所有的部分都是相同的颜色。知道我该如何解决这个问题吗?

代码:

PieChart mChart = (PieChart) findViewById(R.id.piechart);

List<PieEntry> pieChartEntries = new ArrayList<>();

pieChartEntries.add(new PieEntry(18.5f, "Green"));
pieChartEntries.add(new PieEntry(26.7f, "Yellow"));
pieChartEntries.add(new PieEntry(24.0f, "Red"));
pieChartEntries.add(new PieEntry(30.8f, "Blue"));

PieDataSet set = new PieDataSet(pieChartEntries, "Emotion Results");
PieData data = new PieData(set);
mChart.setData(data);
set.setColors(R.color.pieColour1,R.color.pieColour2,R.color.pieColour3,R.color.pieColour4,R.color.pieColour5,R.color.pieColour6,R.color.pieColour7,R.color.pieColour8);
mChart.invalidate();

文档说:

When adding some additional styling, the resulting PieChart with the data used above could look similar to this

这些不是真正的颜色,只是颜色的标签:

pieChartEntries.add(new PieEntry(18.5f, "Green"));
pieChartEntries.add(new PieEntry(26.7f, "Yellow"));
pieChartEntries.add(new PieEntry(24.0f, "Red"));
pieChartEntries.add(new PieEntry(30.8f, "Blue"));

要为您使用的饼图添加颜色:

set.setColors(new int[]{Color.parseColor("#FF32DA64"),
                    Color.parseColor("#FF32DAD4"),
                    Color.parseColor("#FFB853F2"),
                    Color.parseColor("#FFF2ED53")});

或者您可以使用以下模板之一:

set.setColors(ColorTemplate.COLORFUL_COLORS);

编辑:

我刚刚看到您正在使用资源中的颜色,如果您检查 setColors 方法,您应该会看到:

If you are using colors from the resources,make sure that the colors are already prepared (by calling getResources().getColor(...))

因此,在您的情况下,您需要先将资源解析为 Color 个对象,然后再将它们添加到 set