版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wwdlss/article/details/49998877
在上一篇的文章中使用了 hellochart Android统计图表开源框架做了折线图。接着上一篇 这里我们使用hellochart 图表框架做一下饼图。
开源框架的地址是 : https://github.com/lecho/hellocharts-android
一、创建项目 把jar包 hellocharts-library-1.5.8.jar 复制到项目的 libs目录下面。
二 、 在布局文件中引用饼图:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eaeaea" >
<lecho.lib.hellocharts.view.PieChartView
android:id="@+id/pie_chart"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
三、 MainActivity中: (下面关于饼图的一些设置我都有注释,更多其他的功能大家可以摸索一下,下面的基本都够用)
public class MainActivity extends Activity{
private PieChartView pieChart;
private PieChartData pieChardata;
List<SliceValue> values = new ArrayList<SliceValue>();
private int[] data = {21,20,9,2,8,33,14,12};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pieChart = (PieChartView) findViewById(R.id.pie_chart);
pieChart.setOnValueTouchListener(selectListener);//设置点击事件监听
setPieChartData();
initPieChart();
}
/**
* 获取数据
*/
private void setPieChartData(){
for (int i = 0; i < data.length; ++i) {
SliceValue sliceValue = new SliceValue((float) data[i], Utils.pickColor());//这里的颜色是我写了一个工具类 是随机选择颜色的
values.add(sliceValue);
}
}
/**
* 初始化
*/
private void initPieChart() {
pieChardata = new PieChartData();
pieChardata.setHasLabels(true);//显示表情
pieChardata.setHasLabelsOnlyForSelected(false);//不用点击显示占的百分比
pieChardata.setHasLabelsOutside(false);//占的百分比是否显示在饼图外面
pieChardata.setHasCenterCircle(true);//是否是环形显示
pieChardata.setValues(values);//填充数据
pieChardata.setCenterCircleColor(Color.WHITE);//设置环形中间的颜色
pieChardata.setCenterCircleScale(0.5f);//设置环形的大小级别
pieChardata.setCenterText1("饼图测试");//环形中间的文字1
pieChardata.setCenterText1Color(Color.BLACK);//文字颜色
pieChardata.setCenterText1FontSize(14);//文字大小
pieChardata.setCenterText2("饼图测试");
pieChardata.setCenterText2Color(Color.BLACK);
pieChardata.setCenterText2FontSize(18);
/**这里也可以自定义你的字体 Roboto-Italic.ttf这个就是你的字体库*/
// Typeface tf = Typeface.createFromAsset(this.getAssets(), "Roboto-Italic.ttf");
// data.setCenterText1Typeface(tf);
pieChart.setPieChartData(pieChardata);
pieChart.setValueSelectionEnabled(true);//选择饼图某一块变大
pieChart.setAlpha(0.9f);//设置透明度
pieChart.setCircleFillRatio(1f);//设置饼图大小
}
/**
* 监听事件
*/
private PieChartOnValueSelectListener selectListener = new PieChartOnValueSelectListener() {
@Override
public void onValueDeselected() {
// TODO Auto-generated method stub
}
@Override
public void onValueSelected(int arg0, SliceValue value) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Selected: " + value.getValue(), Toast.LENGTH_SHORT).show();
}
};
}
四、现在运行一下看一下效果图:
五、免费分享一下demo:
点击这里下载