Thumbs up to the answer from @m4n3k4s. Just want to add some clarification with regards to these lines, since it took me a while to figure out:
set.setColors(new int[]{ContextCompat.getColor(context, R.color.green),
ContextCompat.getColor(context, R.color.orange),
ContextCompat.getColor(context, R.color.red)});
I didn't know what context
was or how to use it until I found this thread. I replaced the lines above with:
barDataSet.setColors(
ContextCompat.getColor(barchart.getContext(), R.color.green),
ContextCompat.getColor(barchart.getContext(), R.color.yellow),
ContextCompat.getColor(barchart.getContext(), R.color.red)
);
Given that BarChart
is a subclass of View
, and getContext()
is a method of the View
class.
So my complete code looks like this, where KpBarDataSet is my class that overrides BarDataSet, and DateKp is a custom class.
BarChart barchart = (BarChart) findViewById(R.id.barchart);
List<BarEntry> entries = new ArrayList<BarEntry>();
List<String> dateLabels = new ArrayList<>();
int i = 0;
for (DateKp day : data) {
// turn your data into Entry objects
entries.add(new BarEntry(i, day.getValueY()));
dateLabels.add(day.getLabel());
i++;
}
KpBarDataSet barDataSet = new KpBarDataSet(entries, null);
barDataSet.setColors(
ContextCompat.getColor(barchart.getContext(), R.color.green),
ContextCompat.getColor(barchart.getContext(), R.color.yellow),
ContextCompat.getColor(barchart.getContext(), R.color.red)
);
Lastly, R.color.green
, R.color.red
etc won't exist until you define them in /res/values/colors.xml.
Hope this helps.