Gráfico circular en Android usando Jetpack Compose

El gráfico circular se usa en muchas aplicaciones de Android para mostrar una gran cantidad de datos en un formato simple y fácil. Esto se ve en aplicaciones donde se debe manejar una gran cantidad de datos. En este artículo, veremos cómo crear un gráfico circular en Android usando Jetpack Compose . A continuación se muestra un video de muestra para tener una idea de lo que vamos a hacer en este artículo.’

Implementación paso a paso

Paso 1: crea un nuevo proyecto en Android Studio

Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Al elegir la plantilla, seleccione Actividad de composición vacía . Si no encuentra esta plantilla, intente actualizar Android Studio a la última versión. Demostramos la aplicación en Kotlin, así que asegúrese de seleccionar Kotlin como idioma principal al crear un nuevo proyecto.

Paso 2: Agregar dependencia en build.gradle

Navegue a Gradle Scripts > archivo build.gradle y agregue la siguiente dependencia en la sección de dependencias. 

// add below dependency in dependencies section.
implementation "com.github.PhilJay:MPAndroidChart:v3.1.0"

Después de agregar esta dependencia, vaya a Gradle scripts > settings.gradle file y agregue la siguiente línea de código en la sección de repositorios. 

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

Después de agregar esta dependencia, sincronice su proyecto para instalar la dependencia. 

Paso 3: Agregar nuevos colores en el archivo Color.kt

Vaya a la aplicación > java > el nombre del paquete de su aplicación > ui.theme > archivo Color.kt y agréguele el siguiente código. 

Kotlin

package com.example.newcanaryproject.ui.theme
 
import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)
val blueColor = Color(0xFF2196F3)
val yellowColor = Color(0xFFFFC107)
val redColor = Color(0xFFF44336)

Paso 4: Creación de una nueva clase de Kotlin para datos de gráficos circulares

Vaya a la aplicación > java > el nombre del paquete de su aplicación > haga clic con el botón derecho en él > Nuevo > archivo Kotlin/Class y nombre su archivo como PieChartData y agréguele el siguiente código. Se agregan comentarios en el código para conocer en detalle. 

Kotlin

package com.example.newcanaryproject
 
// on below line we are creating data class for
// pie chart data and passing variable as browser
// name and value.
data class PieChartData(
    var browserName: String?,
    var value: Float?
)
 
// on below line we are creating a method
// in which we are passing all the data.
val getPieChartData = listOf(
    PieChartData("Chrome", 34.68F),
    PieChartData("Firefox", 16.60F),
    PieChartData("Safari", 16.15F),
    PieChartData("Internet Explorer", 15.62F),
)

Paso 5: trabajar con el archivo MainActivity.kt

Vaya al archivo MainActivity.kt y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity.kt . Se agregan comentarios dentro del código para comprender el código con más detalle.

Kotlin

package com.example.newcanaryproject
 
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
 
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.Dimension.DP
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Mic
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import androidx.compose.ui.viewinterop.AndroidView
import com.example.newcanaryproject.ui.theme.*
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import org.intellij.lang.annotations.JdkConstants.HorizontalAlignment
import java.util.*
 
class MainActivity : ComponentActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying
                // background color for our application
                Surface(color = MaterialTheme.colors.primary) {
                    // on below line we are
                    // specifying theme as scaffold
                    Scaffold(
                        // on below line we are specifying
                        // top bar as our action bar.
                        topBar = {
                            TopAppBar(
                                // on below line we are specifying title
                                // for our action bar as Speech to Text
                                title = {
                                    Text(
                                        // on below line we are specifying text
                                        // for our text view.
                                        text = "Pie Chart Example",
                                         
                                        // on below line we are specifying
                                        // width of our text
                                        modifier = Modifier.fillMaxWidth(),
                                         
                                        // on below line we are specifying the
                                        // text alignment for our text
                                        textAlign = TextAlign.Center
                                    )
                                })
                        }) {
                        // on below line we are calling pie
                        // chart method to display pie chart.
                        PieChart()
                    }
                }
            }
        }
    }
 
    // on below line we are creating a
    // pie chart function on below line.
    @Composable
    fun PieChart() {
        // on below line we are creating a column
        // and specifying a modifier as max size.
        Column(modifier = Modifier.fillMaxSize()) {
            // on below line we are again creating a column
            // with modifier and horizontal and vertical arrangement
            Column(
                modifier = Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                // on below line we are creating a simple text
                // and specifying a text as Web browser usage share
                Text(
                    text = "Web Browser Usage Share",
                     
                    // on below line we are specifying style for our text
                    style = TextStyle.Default,
                     
                    // on below line we are specifying font family.
                    fontFamily = FontFamily.Default,
                     
                    // on below line we are specifying font style
                    fontStyle = FontStyle.Normal,
                     
                    // on below line we are specifying font size.
                    fontSize = 20.sp
                )
 
                // on below line we are creating a column and
                // specifying the horizontal and vertical arrangement
                // and specifying padding from all sides.
                Column(
                    modifier = Modifier
                        .padding(18.dp)
                        .size(320.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    // on below line we are creating a cross fade and
                    // specifying target state as pie chart data the
                    // method we have created in Pie chart data class.
                    Crossfade(targetState = getPieChartData) { pieChartData ->
                        // on below line we are creating an
                        // android view for pie chart.
                        AndroidView(factory = { context ->
                            // on below line we are creating a pie chart
                            // and specifying layout params.
                            PieChart(context).apply {
                                layoutParams = LinearLayout.LayoutParams(
                                    // on below line we are specifying layout
                                    // params as MATCH PARENT for height and width.
                                    ViewGroup.LayoutParams.MATCH_PARENT,
                                    ViewGroup.LayoutParams.MATCH_PARENT,
                                )
                                // on below line we are setting description
                                // enables for our pie chart.
                                this.description.isEnabled = false
                                 
                                // on below line we are setting draw hole
                                // to false not to draw hole in pie chart
                                this.isDrawHoleEnabled = false
                                 
                                // on below line we are enabling legend.
                                this.legend.isEnabled = true
                                 
                                // on below line we are specifying
                                // text size for our legend.
                                this.legend.textSize = 14F
                                 
                                // on below line we are specifying
                                // alignment for our legend.
                                this.legend.horizontalAlignment =
                                    Legend.LegendHorizontalAlignment.CENTER
                                 
                                // on below line we are specifying entry label color as white.
                                this.setEntryLabelColor(resources.getColor(R.color.white))
                            }
                        },
                            // on below line we are specifying modifier
                            // for it and specifying padding to it.
                            modifier = Modifier
                                .wrapContentSize()
                                .padding(5.dp), update = {
                                // on below line we are calling update pie chart
                                // method and passing pie chart and list of data.
                                updatePieChartWithData(it, pieChartData)
                            })
                    }
                }
            }
        }
    }
 
    // on below line we are creating a update pie
    // chart function to update data in pie chart.
    fun updatePieChartWithData(
        // on below line we are creating a variable
        // for pie chart and data for our list of data.
        chart: PieChart,
        data: List<PieChartData>
    ) {
        // on below line we are creating
        // array list for the entries.
        val entries = ArrayList<PieEntry>()
 
        // on below line we are running for loop for
        // passing data from list into entries list.
        for (i in data.indices) {
            val item = data[i]
            entries.add(PieEntry(item.value ?: 0.toFloat(), item.browserName ?: ""))
        }
 
        // on below line we are creating
        // a variable for pie data set.
        val ds = PieDataSet(entries, "")
         
        // on below line we are specifying color
        // int the array list from colors.
        ds.colors = arrayListOf(
            greenColor.toArgb(),
            blueColor.toArgb(),
            redColor.toArgb(),
            yellowColor.toArgb(),
        )
        // on below line we are specifying position for value
        ds.yValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE
         
        // on below line we are specifying position for value inside the slice.
        ds.xValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE
         
        // on below line we are specifying
        // slice space between two slices.
        ds.sliceSpace = 2f
         
        // on below line we are specifying text color
        ds.valueTextColor = resources.getColor(R.color.white)
         
        // on below line we are specifying
        // text size for value.
        ds.valueTextSize = 18f
         
        // on below line we are specifying type face as bold.
        ds.valueTypeface = Typeface.DEFAULT_BOLD
         
        // on below line we are creating
        // a variable for pie data
        val d = PieData(ds)
         
        // on below line we are setting this
        // pie data in chart data.
        chart.data = d
         
        // on below line we are
        // calling invalidate in chart.
        chart.invalidate()
    }
}

Ahora ejecute su aplicación para ver el resultado. 

Producción:

Publicación traducida automáticamente

Artículo escrito por chaitanyamunje y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *