How to set colors in MPAndroidChart?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 08:26:31

问题


I'm using MPChartlib for a basic "Barchart" (3 bars and values between 0 and 100).

the background of the app is dark so I'd like to put the text in white but when I set the text with color code "FFFFFF" in chart_color stored in string.xml but the text appear in dark blue.

   //Axe X
   XAxis x = barchart.getXAxis();
   x.setPosition(XAxisPosition.BOTTOM);
   x.setTextColor(R.color.chart_color);
   x.setAxisLineColor(R.color.chart_color);


   // Design
   barchart.setDragEnabled(false);
   barchart.setDrawGridBackground(false);
   barchart.setTouchEnabled(false);
   barchart.setHighlightEnabled(false);
   barchart.setMaxVisibleValueCount(101);
   barchart.setDescription(null);
   barchart.setGridBackgroundColor(R.color.chart_color);

   barchart.invalidate(); // refresh

   //Axe Y
   barchart.getAxisLeft().setAxisMaxValue(100);
   barchart.getAxisLeft().setDrawTopYLabelEntry(true);
   barchart.getAxisLeft().setDrawAxisLine(false);
   barchart.getAxisLeft().setDrawGridLines(false);
   barchart.getAxisLeft().setAxisLineColor(R.color.chart_color);
   barchart.getAxisLeft().setTextColor(R.color.chart_color);

   barchart.getAxisRight().setAxisMaxValue(100);
   barchart.getAxisRight().setDrawTopYLabelEntry(true);
   barchart.getAxisRight().setAxisLineColor(R.color.chart_color);
   barchart.getAxisRight().setTextColor(R.color.chart_color);

I tried lots of things and research but couldn't find the issue, does the lib doesn't use the same kind of color code or something ?

Thanks for your help, Alex


回答1:


You are passing the resource id to the library, not the actual color.

Use this to get the color:

    int color = ContextCompat.getColor(context, R.color.chart_color);

    LineDataSet dataSet = ...;
    dataSet.setColor(color);

You can also find this in the documentation.




回答2:


if you want change bars color prefer pass context as well like example below

ArrayList<BarEntry> entries = new ArrayList<>();
        entries.add(new BarEntry(87f, 0));
        entries.add(new BarEntry(90f, 1));


        ArrayList<String> labels = new ArrayList<>();
        labels.add("title 1");
        labels.add("title 2);

        BarDataSet dataSet = new BarDataSet(entries, "# of Calls ");
        BarData barData = new BarData(labels, dataSet);
        dataSet.setColors(new int[]{R.color.color1 , R.color.color2} , context);
        barChart.setData(barData);
        barChart.animateY(3000 , Easing.EasingOption.EaseOutBack );


来源:https://stackoverflow.com/questions/29791086/how-to-set-colors-in-mpandroidchart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!