第一步:添加依赖
在app中的build.gradle中添加:
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
google()
}
}
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
第二步:activity_main.xml中使用PieChart
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/pie_chart"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="300dp"/>
</LinearLayout>
第三步:创建PieChart工具类(PieChartUtil)
import android.graphics.Color;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
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 com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.interfaces.datasets.IPieDataSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PieChartUtil {
//设置各区域颜色
public final int[] PIE_COLORS={
Color.rgb(181, 194, 202), Color.rgb(129, 216, 200)