dbourcet
dbourcet

Reputation: 384

MPAndroidChart Changing slice color after clicking

I successfully followed the YouTube tutorial to draw a PieChart in my app using MPAndroidChart, giving each slice of the pie its own color. I created an OnChartValueSelectedListener so I can know which slice of the pie has been clicked on by the user, like in the following :

public class MyActivity implements OnChartValueSelectedListener {
    @Override
    public void onNothingSelected() {
        // do stuff
    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h){
        Log.i("I clicked on", String.valueOf(e.getXIndex()));
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        ...
        (PieChart)chart = (PieChart) findViewById(R.id.chart);
        ...
        chart.setOnChartValueSelectedListener(this);
    }
}

But even by knowing which slice has been clicked on, I don't seem to find a way to change its color.

The official doc (https://github.com/PhilJay/MPAndroidChart/wiki/Setting-Colors) gives us a way to define and change colors, but only for a dataset, and it seems that a PieChart only have one dataset, so if I change the color of the dataset, every other sliced will see their color changing.

So, I want to know if there is a way, in the following listener

public void onValueSelected(Entry e, int dataSetIndex, Highlight h)

to change the color of the slice which has been clicked on ? Is it a problem you have already faced ?

Upvotes: 2

Views: 2500

Answers (1)

Philipp Jahoda
Philipp Jahoda

Reputation: 51411

Thats quite simple.

Just replace the color value you have set for the DataSet object with a new one.

// get the color(s) you provided for the chart
List<Integer> colors = chart.getData().getDataSetByIndex(dataSetIndex).getColors();

int newcolor = Color.RED;
colors.set(e.getXIndex(), newcolor); // replace the color at the specified index
chart.invalidate(); // refresh

Upvotes: 3

Related Questions