0

I'm using MpAndroidChart for my app. I can create piechart successfully but I have a question. I want an event listener to handle item clicked when user touched one of piechart item.How can I do it?

My Code is as below;

>

int[] ydata = { 5, 2, 3, 1 }; string[] xdata= { "one","two","three","four" };

PieChart pieChart;

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);

    pieChart = FindViewById<PieChart>(Resource.Id.chart1);

    pieChart.RotationEnabled = true;
    pieChart.HoleRadius = 0;
    pieChart.SetTransparentCircleAlpha(0);
    pieChart.SetCenterTextSize(20);
    pieChart.SetDrawEntryLabels(true);
    pieChart.SetUsePercentValues(false);

    pieChart.AnimateX(1000, Easing.EasingOption.EaseInOutCubic);

    pieChart.Description.Text = "test";
    addDataSet();
    pieChart.SetTouchEnabled(true);

}

private void addDataSet()
{
    List<PieEntry> yEntry = new List<PieEntry>();
    List<string> xEntry = new List<string>();

    for (int i = 0; i < ydata.Length; i++)
    {
        yEntry.Add(new PieEntry(ydata[i],xdata[i]));
    }
    for (int i = 0; i < xdata.Length; i++)
    {
        xEntry.Add(xdata[i]);
    }

    PieDataSet piedataset = new PieDataSet(yEntry, "test");

    piedataset.SliceSpace = 0;
    piedataset.ValueTextSize = 20;

    int[] colors= { Color.Blue,Color.Red,Color.Green,Color.White}; 

    piedataset.SetColors(colors);

    Legend legend = pieChart.Legend;

    legend.Form=Legend.LegendForm.Circle;

    PieData pieData = new PieData(piedataset);
    //pieData.SetValueFormatter(new int);

    pieData.SetValueTextColor(Color.White);
    pieChart.Data = (pieData);

    pieChart.Invalidate();
}

1 Answers1

1

You could use SetOnChartValueSelectedListener to set a ChartValueSelectedListener.

For example, in onCreate():

pieChart.SetOnChartValueSelectedListener(new MyListener(this));

And the listener:

public class MyListener : Java.Lang.Object, IOnChartValueSelectedListenerSupport
{
    Context mContext;
    public MyListener(Context context) {
        this.mContext = context;
    }
    public void OnNothingSelected()
    {
       // throw new NotImplementedException();
    }

    public void OnValueSelected(Entry e, Highlight h)
    {
        PieEntry pe = (PieEntry)e;
        Toast.MakeText(mContext, pe.Label+ " is clicked, value is "+ pe.Value, ToastLength.Short).Show();
    }
}

The result is:
enter image description here

Billy Liu - MSFT
  • 2,168
  • 1
  • 8
  • 15