Tổng quan
Ví dụ này minh họa cách vẽ biểu đồ tròn (Pie Chart) trong Android sử dụng thư viện MPAndroidChart.
Các bước thực hiện
Bước 1: Tạo dự án mới
Android Studio → File → New Project → điền thông tin → Finish.
Bước 2: Thêm dependency vào build.gradle (Module)
dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'
// ... các dependency khác
}
Cấu hình packagingOptions tương tự bài Bar Chart để tránh xung đột file META-INF.
Bước 3: Thêm repository JitPack vào build.gradle (Project)
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
}
}
Bước 4: Layout với PieChart (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/pieChart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Bước 5: Code MainActivity.java
package com.example.piechartexample;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
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.utils.ColorTemplate;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private PieChart pieChart;
private PieData pieData;
private PieDataSet pieDataSet;
private ArrayList<PieEntry> pieEntries;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pieChart = findViewById(R.id.pieChart);
getEntries();
pieDataSet = new PieDataSet(pieEntries, "Phân bổ dữ liệu");
pieData = new PieData(pieDataSet);
pieChart.setData(pieData);
// Tùy chỉnh
pieDataSet.setColors(ColorTemplate.JOYFUL_COLORS);
pieDataSet.setSliceSpace(3f);
pieDataSet.setValueTextColor(Color.WHITE);
pieDataSet.setValueTextSize(12f);
pieChart.getDescription().setEnabled(false);
pieChart.setUsePercentValues(true);
pieChart.animateXY(1000, 1000);
}
private void getEntries() {
pieEntries = new ArrayList<>();
pieEntries.add(new PieEntry(20f, "Tháng 1"));
pieEntries.add(new PieEntry(40f, "Tháng 2"));
pieEntries.add(new PieEntry(60f, "Tháng 3"));
pieEntries.add(new PieEntry(80f, "Tháng 4"));
pieEntries.add(new PieEntry(70f, "Tháng 5"));
pieEntries.add(new PieEntry(30f, "Tháng 6"));
}
}
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Màn hình hiển thị biểu đồ tròn với 6 phần tương ứng dữ liệu nhập vào.

Biểu đồ tròn thể hiện tỷ lệ các giá trị dữ liệu mẫu.