Open In App

Android – Create a Pie Chart with Kotlin

Last Updated : 03 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Pie Chart is a circular type of UI interface which is used to display the data in the form of percentages for different categories. This is used to display a vast amount of data. In this article, we will take a look at building a pie chart in an android application using Kotlin. A sample video is given below to get an idea about what we are going to do in this article.

Note: If you are looking to implement Pie Chart in Android using Java. Check out the following article: How to implement Pie Chart in Android using Java

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Add dependency and JitPack Repository

Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.  

implementation ‘com.github.PhilJay:MPAndroidChart:v3.1.0’

Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.

allprojects {
repositories {
  maven { url “https://jitpack.io” }
    }
}

After adding this dependency sync your project and now we will move towards its implementation.  

Step 3: Updating colors in the Colors.xml file

Navigate to app > res > values > colors.xml and add the below code to it to update the color. 

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#0F9D58</color>
    <color name="purple_500">#0F9D58</color>
    <color name="purple_700">#0F9D58</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="grey">#aaa</color>
    <color name="button_color">#1E573B</color>
 
    <color name="yellow">#FFEB3B</color>
    <color name="red">#F44336</color>
</resources>


Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<!--on below line we are creating a swipe to refresh layout-->
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/idTVHead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:gravity="center"
        android:padding="4dp"
        android:text="Pie Chart"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="20sp"
        android:textStyle="bold" />
 
    <!--Ui component for our pie chart-->
    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/pieChart"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_below="@id/idTVHead"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/pieChart"
        android:layout_marginTop="40dp"
        android:orientation="horizontal"
        android:weightSum="3">
 
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:layout_weight="1"
            android:drawableLeft="@drawable/ic_circle"
            android:drawableTint="@color/purple_200"
            android:gravity="center"
            android:padding="4dp"
            android:text="Android"
            android:textAlignment="center"
            android:textColor="@color/black" />
 
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:layout_weight="1"
            android:drawableLeft="@drawable/ic_circle"
            android:drawableTint="@color/yellow"
            android:gravity="center"
            android:padding="4dp"
            android:text="Apple"
            android:textAlignment="center"
            android:textColor="@color/black" />
 
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:layout_weight="1"
            android:drawableLeft="@drawable/ic_circle"
            android:drawableTint="@color/red"
            android:gravity="center"
            android:padding="4dp"
            android:text="Microsoft"
            android:textAlignment="center"
            android:textColor="@color/black" />
    </LinearLayout>
   
</RelativeLayout>


Step 5: Working with the MainActivity.kt file

Navigate to app > java > your app’s package name > MainActivity.kt file and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.PercentFormatter
import com.github.mikephil.charting.utils.MPPointF
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating
    // variables for our pie chart
    lateinit var pieChart: PieChart
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // on below line we are initializing our
        // variable with their ids.
        pieChart = findViewById(R.id.pieChart)
 
        // on below line we are setting user percent value,
        // setting description as enabled and offset for pie chart
        pieChart.setUsePercentValues(true)
        pieChart.getDescription().setEnabled(false)
        pieChart.setExtraOffsets(5f, 10f, 5f, 5f)
 
        // on below line we are setting drag for our pie chart
        pieChart.setDragDecelerationFrictionCoef(0.95f)
 
        // on below line we are setting hole
        // and hole color for pie chart
        pieChart.setDrawHoleEnabled(true)
        pieChart.setHoleColor(Color.WHITE)
 
        // on below line we are setting circle color and alpha
        pieChart.setTransparentCircleColor(Color.WHITE)
        pieChart.setTransparentCircleAlpha(110)
 
        // on  below line we are setting hole radius
        pieChart.setHoleRadius(58f)
        pieChart.setTransparentCircleRadius(61f)
 
        // on below line we are setting center text
        pieChart.setDrawCenterText(true)
 
        // on below line we are setting
        // rotation for our pie chart
        pieChart.setRotationAngle(0f)
         
        // enable rotation of the pieChart by touch
        pieChart.setRotationEnabled(true)
        pieChart.setHighlightPerTapEnabled(true)
 
        // on below line we are setting animation for our pie chart
        pieChart.animateY(1400, Easing.EaseInOutQuad)
 
        // on below line we are disabling our legend for pie chart
        pieChart.legend.isEnabled = false
        pieChart.setEntryLabelColor(Color.WHITE)
        pieChart.setEntryLabelTextSize(12f)
 
        // on below line we are creating array list and
        // adding data to it to display in pie chart
        val entries: ArrayList<PieEntry> = ArrayList()
        entries.add(PieEntry(70f))
        entries.add(PieEntry(20f))
        entries.add(PieEntry(10f))
 
        // on below line we are setting pie data set
        val dataSet = PieDataSet(entries, "Mobile OS")
 
        // on below line we are setting icons.
        dataSet.setDrawIcons(false)
 
        // on below line we are setting slice for pie
        dataSet.sliceSpace = 3f
        dataSet.iconsOffset = MPPointF(0f, 40f)
        dataSet.selectionShift = 5f
 
        // add a lot of colors to list
        val colors: ArrayList<Int> = ArrayList()
        colors.add(resources.getColor(R.color.purple_200))
        colors.add(resources.getColor(R.color.yellow))
        colors.add(resources.getColor(R.color.red))
 
        // on below line we are setting colors.
        dataSet.colors = colors
 
        // on below line we are setting pie data set
        val data = PieData(dataSet)
        data.setValueFormatter(PercentFormatter())
        data.setValueTextSize(15f)
        data.setValueTypeface(Typeface.DEFAULT_BOLD)
        data.setValueTextColor(Color.WHITE)
        pieChart.setData(data)
 
        // undo all highlights
        pieChart.highlightValues(null)
 
        // loading chart
        pieChart.invalidate()
 
    }
}


Now run your application to see the output of it. 

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads