Si usted está pensando en trazar gráficos en su próximo proyecto entonces este tutorial es para usted. En este tutorial queremos ver las mejores librerías de gráficos para Android y cómo utilizarlas.

(a). MPAndroidChart

Una poderosa librería de gráficos para Android, que soporta gráficos de líneas, barras, tartas, burbujas y velas, así como escalado, desplazamiento y animaciones.

Estas son las características que soporta:

  • Muchos tipos de gráficos diferentes: LineChart, BarChart (vertical, horizontal, apilado, agrupado), PieChart, ScatterChart, CandleStickChart (para datos financieros), RadarChart (gráfico de telaraña), BubbleChart
  • Gráficos combinados (por ejemplo, líneas y barras en uno)
  • Escala en ambos ejes (con gesto táctil, ejes por separado o zoom de pellizco)
  • Arrastrar/desplazar (con gesto táctil)
  • Ejes Y separados (dobles)
  • Resaltar los valores (con vistas emergentes personalizables)
  • Guardar el gráfico en la tarjeta SD (como imagen)
  • Plantillas de color predefinidas
  • Leyendas (generadas automáticamente, personalizables)
  • Ejes personalizables (tanto en el eje x como en el eje y)
  • Animaciones (creación de animaciones, tanto en el eje x como en el eje y)
  • Líneas de límite (proporcionan información adicional, máximos, ...)
  • Receptores de llamadas de toque, gesto y selección
  • Totalmente personalizable (pinturas, tipos de letra, leyendas, colores, fondo, líneas discontinuas, ...)
  • Soporte de la base de datos móvil Realm.io a través de la biblioteca MPAndroidChart-Realm
  • Renderizado suave para hasta 10.000 puntos de datos en LineChart y BarChart (probado en un OnePlus One de 2014 con Android 6.0)
  • Ligero (número de métodos ~1.4K)
  • Disponible como archivo .jar (sólo 500kb de tamaño)
  • Disponible como dependencia de Gradle y a través de maven.
  • Aplicación de demostración de Google-PlayStore](https://play.google.com/store/apps/details?id=com.xxmassdeveloper.mpchartexample)
  • Ampliamente utilizado, gran apoyo tanto en GitHub como en stackoverflow - mpandroidchart
  • También disponible para iOS: Charts (la API funciona igual)
  • También disponible para Xamarin: MPAndroidChart.Xamarin
  • Soporte limitado para datos dinámicos y en tiempo real

Paso 1: Instalación

Comienza registrando jitpack como una Url de maven en tu build.gradle de nivel raíz:

repositories {
    maven { url 'https://jitpack.io' }
}

Ahora ve al build.gradle a nivel de aplicación y declara la dependencia:

dependencies {
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}

Paso 2: Ejemplo

Aquí hay un ejemplo de actividad de creación de BarChart usando esta biblioteca:

public class BarChartActivity extends DemoBase implements OnSeekBarChangeListener,
        OnChartValueSelectedListener {

    private BarChart chart;
    private SeekBar seekBarX, seekBarY;
    private TextView tvX, tvY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_barchart);

        setTitle("BarChartActivity");

        tvX = findViewById(R.id.tvXMax);
        tvY = findViewById(R.id.tvYMax);

        seekBarX = findViewById(R.id.seekBar1);
        seekBarY = findViewById(R.id.seekBar2);

        seekBarY.setOnSeekBarChangeListener(this);
        seekBarX.setOnSeekBarChangeListener(this);

        chart = findViewById(R.id.chart1);
        chart.setOnChartValueSelectedListener(this);

        chart.setDrawBarShadow(false);
        chart.setDrawValueAboveBar(true);

        chart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        chart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        chart.setPinchZoom(false);

        chart.setDrawGridBackground(false);
        // chart.setDrawYLabels(false);

        IAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(chart);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxisPosition.BOTTOM);
        xAxis.setTypeface(tfLight);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        xAxis.setValueFormatter(xAxisFormatter);

        IAxisValueFormatter custom = new MyAxisValueFormatter();

        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setTypeface(tfLight);
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setTypeface(tfLight);
        rightAxis.setLabelCount(8, false);
        rightAxis.setValueFormatter(custom);
        rightAxis.setSpaceTop(15f);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        Legend l = chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setForm(LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(11f);
        l.setXEntrySpace(4f);

        XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);
        mv.setChartView(chart); // For bounds control
        chart.setMarker(mv); // Set the marker to the chart

        // setting data
        seekBarY.setProgress(50);
        seekBarX.setProgress(12);

        // chart.setDrawLegend(false);
    }

    private void setData(int count, float range) {

        float start = 1f;

        ArrayList<BarEntry> values = new ArrayList<>();

        for (int i = (int) start; i < start + count; i++) {
            float val = (float) (Math.random() * (range + 1));

            if (Math.random() * 100 < 25) {
                values.add(new BarEntry(i, val, getResources().getDrawable(R.drawable.star)));
            } else {
                values.add(new BarEntry(i, val));
            }
        }

        BarDataSet set1;

        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();

        } else {
            set1 = new BarDataSet(values, "The year 2017");

            set1.setDrawIcons(false);

            int startColor1 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
            int startColor2 = ContextCompat.getColor(this, android.R.color.holo_blue_light);
            int startColor3 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
            int startColor4 = ContextCompat.getColor(this, android.R.color.holo_green_light);
            int startColor5 = ContextCompat.getColor(this, android.R.color.holo_red_light);
            int endColor1 = ContextCompat.getColor(this, android.R.color.holo_blue_dark);
            int endColor2 = ContextCompat.getColor(this, android.R.color.holo_purple);
            int endColor3 = ContextCompat.getColor(this, android.R.color.holo_green_dark);
            int endColor4 = ContextCompat.getColor(this, android.R.color.holo_red_dark);
            int endColor5 = ContextCompat.getColor(this, android.R.color.holo_orange_dark);

            List<Fill> gradientFills = new ArrayList<>();
            gradientFills.add(new Fill(startColor1, endColor1));
            gradientFills.add(new Fill(startColor2, endColor2));
            gradientFills.add(new Fill(startColor3, endColor3));
            gradientFills.add(new Fill(startColor4, endColor4));
            gradientFills.add(new Fill(startColor5, endColor5));

            set1.setFills(gradientFills);

            ArrayList<IBarDataSet> dataSets = new ArrayList<>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setValueTypeface(tfLight);
            data.setBarWidth(0.9f);

            chart.setData(data);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.bar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.viewGithub: {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse("https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/com/xxmassdeveloper/mpchartexample/BarChartActivity.java"));
                startActivity(i);
                break;
            }
            case R.id.actionToggleValues: {
                for (IDataSet set : chart.getData().getDataSets())
                    set.setDrawValues(!set.isDrawValuesEnabled());

                chart.invalidate();
                break;
            }
            case R.id.actionToggleIcons: {
                for (IDataSet set : chart.getData().getDataSets())
                    set.setDrawIcons(!set.isDrawIconsEnabled());

                chart.invalidate();
                break;
            }
            case R.id.actionToggleHighlight: {
                if (chart.getData() != null) {
                    chart.getData().setHighlightEnabled(!chart.getData().isHighlightEnabled());
                    chart.invalidate();
                }
                break;
            }
            case R.id.actionTogglePinch: {
                if (chart.isPinchZoomEnabled())
                    chart.setPinchZoom(false);
                else
                    chart.setPinchZoom(true);

                chart.invalidate();
                break;
            }
            case R.id.actionToggleAutoScaleMinMax: {
                chart.setAutoScaleMinMaxEnabled(!chart.isAutoScaleMinMaxEnabled());
                chart.notifyDataSetChanged();
                break;
            }
            case R.id.actionToggleBarBorders: {
                for (IBarDataSet set : chart.getData().getDataSets())
                    ((BarDataSet) set).setBarBorderWidth(set.getBarBorderWidth() == 1.f ? 0.f : 1.f);

                chart.invalidate();
                break;
            }
            case R.id.animateX: {
                chart.animateX(2000);
                break;
            }
            case R.id.animateY: {
                chart.animateY(2000);
                break;
            }
            case R.id.animateXY: {
                chart.animateXY(2000, 2000);
                break;
            }
            case R.id.actionSave: {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    saveToGallery();
                } else {
                    requestStoragePermission(chart);
                }
                break;
            }
        }
        return true;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        tvX.setText(String.valueOf(seekBarX.getProgress()));
        tvY.setText(String.valueOf(seekBarY.getProgress()));

        setData(seekBarX.getProgress(), seekBarY.getProgress());
        chart.invalidate();
    }

    @Override
    protected void saveToGallery() {
        saveToGallery(chart, "BarChartActivity");
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {}

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {}

    private final RectF onValueSelectedRectF = new RectF();

    @Override
    public void onValueSelected(Entry e, Highlight h) {

        if (e == null)
            return;

        RectF bounds = onValueSelectedRectF;
        chart.getBarBounds((BarEntry) e, bounds);
        MPPointF position = chart.getPosition(e, AxisDependency.LEFT);

        Log.i("bounds", bounds.toString());
        Log.i("position", position.toString());

        Log.i("x-index",
                "low: " + chart.getLowestVisibleX() + ", high: "
                        + chart.getHighestVisibleX());

        MPPointF.recycleInstance(position);
    }

    @Override
    public void onNothingSelected() { }
}

Hay docenas de ejemplos de este tipo en el enlace de descarga que se proporciona a continuación.

Referencia

Descargue o lea más en los siguientes enlaces:

Número Enlace
1. Descargar Ejemplo
2. Leer más

(b). AndroidCharts

Una biblioteca de gráficos para Android fácil de usar y con animación.

AndroidCharts Example

Paso 1: Instalarlo

En tu app/build.gradle añade la siguiente declaración de implementación y sincronización:

implementation 'im.dacer:AndroidCharts:1.0.4'

Paso 2: Añadir al Layout

Añade al layout lo siguiente:

Ejemplo de gráfico de líneas

<HorizontalScrollView>
        <view
            android:layout_width="wrap_content"
            android:layout_height="300dp"
            class="im.dacer.androidcharts.LineView"
            android:id="@+id/line_view" />
</HorizontalScrollView>

Ejemplo de gráfico de barras

<HorizontalScrollView>
        <view
            android:layout_width="wrap_content"
            android:layout_height="300dp"
            class="im.dacer.androidcharts.BarView"
            android:id="@+id/bar_view" />
</HorizontalScrollView>

Gráfico de tarta

En esta vista dibujaremos un gráfico de tarta:

<view
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    class="im.dacer.androidcharts.PieView"
    android:id="@+id/pie_view" />

Paso 3: Escribir el código

Haz referencia a la vista del gráfico y adjunta los datos a la misma:

Ejemplo de gráfico de líneas

LineView lineView = (LineView)findViewById(R.id.line_view);
lineView.setDrawDotLine(false); //optional
lineView.setShowPopup(LineView.SHOW_POPUPS_MAXMIN_ONLY); //optional
lineView.setBottomTextList(strList);
lineView.setColorArray(new int[]{Color.BLACK,Color.GREEN,Color.GRAY,Color.CYAN});
lineView.setDataList(dataLists); //or lineView.setFloatDataList(floatDataLists)

Ejemplo de gráfico de barras

Así es como se dibuja el BarChart:

BarView barView = (BarView)findViewById(R.id.bar_view);\
barView.setBottomTextList(strList);
barView.setDataList(dataList,100);

Gráfico de Pastel

Así es como se dibuja el PirChart

PieView pieView = (PieView)findViewById(R.id.pie_view);
ArrayList<PieHelper> pieHelperArrayList = new ArrayList<PieHelper>();
pieView.setDate(pieHelperArrayList);
pieView.selectedPie(2); //optional
pieView.setOnPieClickListener(listener) //optional
pieView.showPercentLabel(false); //optional

Ejemplo completo

Fragmento de Barra

Aquí hay un ejemplo de un Fragmento que renderiza BarChart:

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import im.dacer.androidcharts.BarView;
import java.util.ArrayList;

/**
 * Created by Dacer on 11/15/13.
 */
public class BarFragment extends Fragment {
    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_bar, container, false);
        final BarView barView = (BarView) rootView.findViewById(R.id.bar_view);
        Button button = (Button) rootView.findViewById(R.id.bar_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View view) {
                randomSet(barView);
            }
        });
        randomSet(barView);
        return rootView;
    }

    private void randomSet(BarView barView) {
        int random = (int) (Math.random() * 20) + 6;
        ArrayList<String> test = new ArrayList<String>();
        for (int i = 0; i < random; i++) {
            test.add("test");
            test.add("pqg");
            //            test.add(String.valueOf(i+1));
        }
        barView.setBottomTextList(test);

        ArrayList<Integer> barDataList = new ArrayList<Integer>();
        for (int i = 0; i < random * 2; i++) {
            barDataList.add((int) (Math.random() * 100));
        }
        barView.setDataList(barDataList, 100);
    }
}

Encuentre más ejemplos aquí.

Referencia

A continuación, los enlaces de referencia:

Número Enlace
1. Descargar Ejemplo
2. Leer más

(c). HelloCharts

Biblioteca de gráficos para Android compatible con la API 8+, varios tipos de gráficos con soporte para escalado, desplazamiento y animaciones.

Tenga en cuenta que funciona mejor cuando la aceleración por hardware está disponible, por lo que se recomienda la API 14+(Android 4.0). Licencia Apache 2.0.

Estas son sus características principales:

  • Gráfico de líneas (líneas cúbicas, líneas rellenas, puntos dispersos)
  • Gráfico de columnas (agrupado, apilado, valores negativos)
  • Gráfico circular
  • Gráfico de burbujas
  • Gráfico combinado (columnas/líneas)
  • Vista previa de los gráficos (de columnas y de líneas)
  • Zoom (pellizcar para hacer zoom, doble toque para hacer zoom), desplazamiento y fling
  • Ejes personalizados y autogenerados (superior, inferior, izquierdo, derecho, interior)
  • Animaciones

Paso 1: Instalarlo

Sus dos repositorios desde los que puedes instalar esta librería:

MavenCentral

implementation 'com.github.lecho:hellocharts-library:1.5.8@aar'

Jitpack

Desde Jitpack empieza registrando jitpack como repositorio de maven:

   repositories {
       maven {
           url "https://jitpack.io"
       }
   }

Luego añade la dependencia:

   dependencies {
       implementaion 'com.github.lecho:hellocharts-android:v1.5.8'
   }

Eclipse

  • Descargue la última release jar file.
  • Copie hellocharts-library-<version>.jar en la carpeta libs de su proyecto de aplicación.

Paso 2: Añadir al diseño

Añada los HelloCharts apropiados a su diseño, por ejemplo para un LineChart:

   <lecho.lib.hellocharts.view.LineChartView
       android:id="@+id/chart"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />

Paso 3: Escribir el código

Puede hacer referencia al gráfico o crearlo mediante programación:

   LineChartView chart = new LineChartView(context);
   layout.addView(chart);

A continuación, controle el comportamiento del Gráfico:

   Chart.setInteractive(boolean isInteractive);
   Chart.setZoomType(ZoomType zoomType);
   Chart.setContainerScrollEnabled(boolean isEnabled, ContainerScrollType type);

Luego utilizar los métodos del modelo de datos para controlar el aspecto del gráfico:

   ChartData.setAxisXBottom(Axis axisX);
   ColumnChartData.setStacked(boolean isStacked);
   Line.setStrokeWidth(int strokeWidthDp);

Configurar los datos y el modelo del Gráfico en función del tipo de Gráfico utilizado:

   List<PointValue> values = new ArrayList<PointValue>();
   values.add(new PointValue(0, 2));
   values.add(new PointValue(1, 4));
   values.add(new PointValue(2, 3));
   values.add(new PointValue(3, 4));

   //In most cased you can call data model methods in builder-pattern-like manner.
   Line line = new Line(values).setColor(Color.BLUE).setCubic(true);
   List<Line> lines = new ArrayList<Line>();
   lines.add(line);

   LineChartData data = new LineChartData();
   data.setLines(lines);

   LineChartView chart = new LineChartView(context);
   chart.setLineChartData(data);

Ejemplo

Este es un ejemplo de PieChart:

PieChartActivity.java

public class PieChartActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pie_chart);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    /**
     * A fragment containing a pie chart.
     */
    public static class PlaceholderFragment extends Fragment {

        private PieChartView chart;
        private PieChartData data;

        private boolean hasLabels = false;
        private boolean hasLabelsOutside = false;
        private boolean hasCenterCircle = false;
        private boolean hasCenterText1 = false;
        private boolean hasCenterText2 = false;
        private boolean isExploded = false;
        private boolean hasLabelForSelected = false;

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            setHasOptionsMenu(true);
            View rootView = inflater.inflate(R.layout.fragment_pie_chart, container, false);

            chart = (PieChartView) rootView.findViewById(R.id.chart);
            chart.setOnValueTouchListener(new ValueTouchListener());

            generateData();

            return rootView;
        }

        // MENU
        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.pie_chart, menu);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == R.id.action_reset) {
                reset();
                generateData();
                return true;
            }
            if (id == R.id.action_explode) {
                explodeChart();
                return true;
            }
            if (id == R.id.action_center_circle) {
                hasCenterCircle = !hasCenterCircle;
                if (!hasCenterCircle) {
                    hasCenterText1 = false;
                    hasCenterText2 = false;
                }

                generateData();
                return true;
            }
            if (id == R.id.action_center_text1) {
                hasCenterText1 = !hasCenterText1;

                if (hasCenterText1) {
                    hasCenterCircle = true;
                }

                hasCenterText2 = false;

                generateData();
                return true;
            }
            if (id == R.id.action_center_text2) {
                hasCenterText2 = !hasCenterText2;

                if (hasCenterText2) {
                    hasCenterText1 = true;// text 2 need text 1 to by also drawn.
                    hasCenterCircle = true;
                }

                generateData();
                return true;
            }
            if (id == R.id.action_toggle_labels) {
                toggleLabels();
                return true;
            }
            if (id == R.id.action_toggle_labels_outside) {
                toggleLabelsOutside();
                return true;
            }
            if (id == R.id.action_animate) {
                prepareDataAnimation();
                chart.startDataAnimation();
                return true;
            }
            if (id == R.id.action_toggle_selection_mode) {
                toggleLabelForSelected();
                Toast.makeText(getActivity(),
                        "Selection mode set to " + chart.isValueSelectionEnabled() + " select any point.",
                        Toast.LENGTH_SHORT).show();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        private void reset() {
            chart.setCircleFillRatio(1.0f);
            hasLabels = false;
            hasLabelsOutside = false;
            hasCenterCircle = false;
            hasCenterText1 = false;
            hasCenterText2 = false;
            isExploded = false;
            hasLabelForSelected = false;
        }

        private void generateData() {
            int numValues = 6;

            List<SliceValue> values = new ArrayList<SliceValue>();
            for (int i = 0; i < numValues; ++i) {
                SliceValue sliceValue = new SliceValue((float) Math.random() * 30 + 15, ChartUtils.pickColor());
                values.add(sliceValue);
            }

            data = new PieChartData(values);
            data.setHasLabels(hasLabels);
            data.setHasLabelsOnlyForSelected(hasLabelForSelected);
            data.setHasLabelsOutside(hasLabelsOutside);
            data.setHasCenterCircle(hasCenterCircle);

            if (isExploded) {
                data.setSlicesSpacing(24);
            }

            if (hasCenterText1) {
                data.setCenterText1("Hello!");

                // Get roboto-italic font.
                Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Italic.ttf");
                data.setCenterText1Typeface(tf);

                // Get font size from dimens.xml and convert it to sp(library uses sp values).
                data.setCenterText1FontSize(ChartUtils.px2sp(getResources().getDisplayMetrics().scaledDensity,
                        (int) getResources().getDimension(R.dimen.pie_chart_text1_size)));
            }

            if (hasCenterText2) {
                data.setCenterText2("Charts (Roboto Italic)");

                Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Italic.ttf");

                data.setCenterText2Typeface(tf);
                data.setCenterText2FontSize(ChartUtils.px2sp(getResources().getDisplayMetrics().scaledDensity,
                        (int) getResources().getDimension(R.dimen.pie_chart_text2_size)));
            }

            chart.setPieChartData(data);
        }

        private void explodeChart() {
            isExploded = !isExploded;
            generateData();

        }

        private void toggleLabelsOutside() {
            // has labels have to be true:P
            hasLabelsOutside = !hasLabelsOutside;
            if (hasLabelsOutside) {
                hasLabels = true;
                hasLabelForSelected = false;
                chart.setValueSelectionEnabled(hasLabelForSelected);
            }

            if (hasLabelsOutside) {
                chart.setCircleFillRatio(0.7f);
            } else {
                chart.setCircleFillRatio(1.0f);
            }

            generateData();

        }

        private void toggleLabels() {
            hasLabels = !hasLabels;

            if (hasLabels) {
                hasLabelForSelected = false;
                chart.setValueSelectionEnabled(hasLabelForSelected);

                if (hasLabelsOutside) {
                    chart.setCircleFillRatio(0.7f);
                } else {
                    chart.setCircleFillRatio(1.0f);
                }
            }

            generateData();
        }

        private void toggleLabelForSelected() {
            hasLabelForSelected = !hasLabelForSelected;

            chart.setValueSelectionEnabled(hasLabelForSelected);

            if (hasLabelForSelected) {
                hasLabels = false;
                hasLabelsOutside = false;

                if (hasLabelsOutside) {
                    chart.setCircleFillRatio(0.7f);
                } else {
                    chart.setCircleFillRatio(1.0f);
                }
            }

            generateData();
        }

        /**
         * To animate values you have to change targets values and then call {@link Chart#startDataAnimation()}
         * method(don't confuse with View.animate()).
         */
        private void prepareDataAnimation() {
            for (SliceValue value : data.getValues()) {
                value.setTarget((float) Math.random() * 30 + 15);
            }
        }

        private class ValueTouchListener implements PieChartOnValueSelectListener {

            @Override
            public void onValueSelected(int arcIndex, SliceValue value) {
                Toast.makeText(getActivity(), "Selected: " + value, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onValueDeselected() {
                // TODO Auto-generated method stub

            }

        }
    }
}

Puedes encontrar el código de ejemplo completo aquí

Referencia

Encuentre el enlace de descarga a continuación:

Descargar Ejemplo
Leer más
Seguir al autor de la biblioteca

Categorizado en: