首先附上效果圖:
1.添加依賴
//在build.gradle(Module:app)下添加
implementation'com.github.PhilJay:MPAndroidChart:v3.0.3'
//在build.gradle(Project:你的項(xiàng)目名稱)下的allprojects中添加
maven {
url"https://jitpack.io"
}
2.新建布局
<com.github.mikephil.charting.charts.BarChart
? ? android:id="@+id/barchart"
? ? android:layout_width="394dp"
? ? android:layout_height="394dp"
? ? android:layout_gravity="center" />
3.造數(shù)據(jù)(有詳細(xì)注釋)
private Map> getData(){
//造了兩條數(shù)據(jù)
? ? List list=new ArrayList<>();
for (int i=1;i<=9;i=i+2){
list.add(new BarEntry(i, (float) Math.round((Math.random())*10)+1));
}
List list1=new ArrayList<>();
for (int i=2;i<=10;i=i+2){
list1.add(new BarEntry(i, (float) Math.round((Math.random())*10)+1));
}
HashMap> map=new HashMap<>();
map.put("man",list);
map.put("girl",list1);
return map;
}
4.數(shù)據(jù)裝載(有詳細(xì)注釋)
private void showBarChart(Map> map,BarChart barChart){
//裝載男女生數(shù)據(jù)
? ? BarDataSet barDataSet=new BarDataSet(map.get("man"),"男生");
barDataSet.setColor(Color.rgb(199,255,140));
BarDataSet barDataSet1=new BarDataSet(map.get("girl"),"女生");
barDataSet1.setColor(Color.rgb(255,240,157));
//載入數(shù)據(jù)集
? ? BarData barData=new BarData();
barData.addDataSet(barDataSet);
barData.addDataSet(barDataSet1);
barChart.setData(barData);
//可以用它來(lái)設(shè)置圖的大小顯示
? ? barChart.setExtraOffsets(15,80,20,45);
//右下角標(biāo)識(shí)描述,需要可以打開
? ? Description description=new Description();
description.setText("柱狀圖");
description.setEnabled(false);
barChart.setDescription(description);
//將x軸設(shè)置在下方
? ? XAxis xAxis=barChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setAxisMinimum(0);
xAxis.setLabelCount(10);
//設(shè)置y軸右邊不顯示
? ? YAxis yAxis=barChart.getAxisRight();
yAxis.setEnabled(false);
YAxis yy=barChart.getAxisLeft();
yy.setAxisMinimum(0);
yy.setAxisMaximum(10);
yy.setLabelCount(100);
barChart.setScaleEnabled(false);//設(shè)置不能縮放
}
5.初始化組件齐媒,調(diào)用方法即可
barChart=this.findViewById(R.id.barchart);
showBarChart(getData(),barChart);
代碼中的注釋記得仔細(xì)看哦