4

I want to set a specific color for a bar in BarChart from MPAndroidChart. I do everything according to a documentation, but the color isn't changing. Here's my code:

   barChart = (BarChart) findViewById(R.id.bar_chart);
   List<BarEntry> entries = new ArrayList<BarEntry>();
   entries.add(new BarEntry(1.0f, 10.0f)); //tmp values

   BarDataSet dataSet = new BarDataSet(entries, "bars");
   dataSet.setColor(R.color.red); //color from resourses

   BarData barData = new BarData(dataSet);

   barChart.setData(barData);
   barChart.invalidate(); 

The funny thing is that before I tried to change the color of the bar, the bar was blue, after I tried to change its color, it became grey (no matter, what color it must be). I don't understand why doesn't the color change. I also tried to override getColor method in the BarDataSet class, but result is the same -- bar is grey.

Grey, but not red

Aleksandr Tukallo
  • 1,299
  • 17
  • 22

4 Answers4

17

Change this line,

dataSet.setColor(R.color.red); //resource id of a color

to,

dataSet.setColor(getResources().getColor(R.color.red)); //resolved color

When you call setColor you need to pass in an integer that represents an RGB triple. R.color.red is not an RGB triple but instead an integer that represents a resource in R.java.

See this question for more about the difference between a resource id and a resolved color.

David Rawson
  • 20,912
  • 7
  • 88
  • 124
Magesh Pandian
  • 8,789
  • 12
  • 45
  • 60
  • Thank you! It works perfectly, but why should I write in this way? What was not correct in my code? And, moreover, Android Studio says, that 'getColor' method is deprecated. What should I use instead of it? – Aleksandr Tukallo Dec 08 '16 at 13:07
  • 3
    I found out, that I should use `ContextCompat.getColor()` instead of deprecated `getResourses().getColor()`, but first quistion still remains. – Aleksandr Tukallo Dec 08 '16 at 14:55
2
  BarDataSet dataSet = new BarDataSet(entries, "bars");
   dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
Gautam Dev
  • 399
  • 2
  • 4
1

If you want to set color, you can create and array of color. Then set that array to Bardataset. Example is given Below.

int[] colors = {Color.rgb(153, 193, 12), Color.rgb(179, 130, 76)};

    Bardataset.setColors(colors);

I think you should write Your code in this sequence. Take a look below :

      BarDataSet dataSet = new BarDataSet(entries, "bars");
      dataSet.setColor(Color.parseColor("#104E78"));
      BarData barData = new BarData(dataSet);

Try it.

Yogesh Nandha
  • 175
  • 1
  • 11
0

We can change color this way.

    bardataset.setColors(new int[]{getResources().getColor(R.color.red)});
suprita
  • 211
  • 1
  • 9