MpAndroidChart绘制饼状图
时间: 2023-09-30 21:07:48 浏览: 44
1. 添加依赖
在项目的build.gradle文件中添加以下依赖:
```
dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}
```
2. 在布局中添加PieChart视图
在布局文件中添加PieChart视图:
```
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/pie_chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3. 准备数据
准备数据,创建一个PieEntry列表:
```
List<PieEntry> entries = new ArrayList<>();
entries.add(new PieEntry(10f, "A"));
entries.add(new PieEntry(20f, "B"));
entries.add(new PieEntry(30f, "C"));
entries.add(new PieEntry(40f, "D"));
```
4. 创建PieDataSet
使用PieEntry列表创建PieDataSet:
```
PieDataSet dataSet = new PieDataSet(entries, "Label");
dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
dataSet.setValueTextSize(16f);
```
5. 创建PieData
使用PieDataSet创建PieData:
```
PieData data = new PieData(dataSet);
```
6. 配置PieChart
配置PieChart的属性:
```
PieChart pieChart = findViewById(R.id.pie_chart);
pieChart.setData(data);
pieChart.setHoleRadius(50f);
pieChart.setTransparentCircleRadius(55f);
pieChart.setEntryLabelColor(Color.BLACK);
pieChart.setEntryLabelTextSize(16f);
pieChart.getDescription().setEnabled(false);
pieChart.getLegend().setEnabled(false);
pieChart.animateY(1000, Easing.EaseInOutCubic);
```
7. 运行程序
运行程序,即可看到绘制的饼状图。