MPAndroidChart: negative values in pie chart or custom labels

断了今生、忘了曾经 提交于 2019-12-25 04:33:26

问题


In my Android application I have to show my income and expense amounts in a piechart. The expense amounts will be negative. The amounts are of type float. So is it possible to display both negative and positive values in a pie chart using MPAndroidChart library?

I have tried with some negative and positive integer values and the result is horible. The pie-chart will behave crazy like a rummy board or illumination screen.

If I can't have negative values in a pie chart, is it possible to show the labels in negative by even though the actual values are positive?


回答1:


You are essentially asking how to customise the labels on an MPAndroidChart chart. This can be done easily by writing your own implementation of the interface IValueFormatter.

IValueFormatter has one method that you need to implement:

getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler)`

You use the parameters of the method to construct the label you want as a String. You want a minus sign "-" in front so you simply do this:

return "-" + mFormat.format(value) + " %";

Here is the complete implementation:

public class NegativePercentFormatter implements IValueFormatter

    protected DecimalFormat mFormat;

    public NegativePercentFormatter() {
        mFormat = new DecimalFormat("###,###,##0.0");
    }


    public NegativePercentFormatter(DecimalFormat format) {
        this.mFormat = format;
    }

    @Override
    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
        return "-" + mFormat.format(value) + " %";
    }
}


来源:https://stackoverflow.com/questions/41075105/mpandroidchart-negative-values-in-pie-chart-or-custom-labels

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