Android 实现会旋转的饼状统计图实例代码
作者:lqh 发布时间:2022-04-08 09:38:50
标签:Android,饼状,统计图
Android 实现会旋转的饼状统计图实例代码
最近在做一个项目,由于有需要统计的需要,于是就做成了下面饼状统计图。
下图是效果图:
大致思路是:
关于的介绍这里不做详细介绍,如果想深入请点击开源项目MPAndroidChart
下面是其实现:
首先是添加MPAndroidChart依赖:
maven { url "https://jitpack.io" }
compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'
Mainactivity
package com.example.geekp.myapplication;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
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.utils.ColorTemplate;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
getSupportActionBar().setTitle("饼状统计图");
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
//fragment
public static class PlaceholderFragment extends Fragment {
@BindView(R.id.chart1)
PieChart mChart;
@BindView(R.id.tvXMax)
TextView tvXMax;
@BindView(R.id.tvYMax)
TextView tvYMax;
protected String[] mParties = new String[]{
"已完成", "未完成"
};
protected Typeface mTfRegular;
protected Typeface mTfLight;
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.bind(this, rootView);
int index = getArguments().getInt(ARG_SECTION_NUMBER);
mTfRegular = Typeface.createFromAsset(getContext().getAssets(), "OpenSans-Regular.ttf");
mTfLight = Typeface.createFromAsset(getContext().getAssets(), "OpenSans-Light.ttf");
mChart.setUsePercentValues(true);
mChart.getDescription().setEnabled(false);
mChart.setExtraOffsets(5, 10, 5, 5);
mChart.setDragDecelerationFrictionCoef(0.95f);
mChart.setCenterTextTypeface(mTfLight);
mChart.setCenterText(generateCenterSpannableText(index));
mChart.setDrawHoleEnabled(true);
mChart.setHoleColor(Color.WHITE);
mChart.setTransparentCircleColor(Color.WHITE);
mChart.setTransparentCircleAlpha(110);
mChart.setHoleRadius(58f);
mChart.setTransparentCircleRadius(61f);
mChart.setDrawCenterText(true);
mChart.setRotationAngle(0);
// enable rotation of the chart by touch
mChart.setRotationEnabled(true);
mChart.setHighlightPerTapEnabled(true);
setData(index);
mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
// mChart.spin(2000, 0, 360);
Legend l = mChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
l.setXEntrySpace(7f);
l.setYEntrySpace(0f);
l.setYOffset(0f);
// entry label styling
mChart.setEntryLabelColor(Color.WHITE);
mChart.setEntryLabelTypeface(mTfRegular);
mChart.setEntryLabelTextSize(12f);
return rootView;
}
//饼状图中间要显示的内容
private SpannableString generateCenterSpannableText(int index) {
String sectionName = "";
switch (index) {
case 1:
sectionName = "科目一";
break;
case 2:
sectionName = "科目二";
break;
case 3:
sectionName = "科目三";
break;
case 4:
sectionName = "科目四";
break;
}
SpannableString s = new SpannableString(sectionName);
s.setSpan(new RelativeSizeSpan(1.7f), 0, sectionName.length(), 0);
return s;
}
private void setData(int fragmentIndex) {
ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
PieDataSet dataSet = new PieDataSet(entries, "正确率:" + 25 + "%");
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
ArrayList<Integer> colors = new ArrayList<Integer>();
if (fragmentIndex == 1) {
//这里写的是饼状图的组成部分,像我这样写就是第一部分是占百分之七十五,第二部分是占了百分之二十五
entries.add(new PieEntry(75, mParties[0]));
entries.add(new PieEntry(25, mParties[1]));
for (int c : ColorTemplate.VORDIPLOM_COLORS)
colors.add(c);
} else if (fragmentIndex == 2) {
entries.add(new PieEntry(50, mParties[0]));
entries.add(new PieEntry(50, mParties[1]));
colors.add(getResources().getColor(R.color.piecolor8));
colors.add(getResources().getColor(R.color.piecolor2));
} else if (fragmentIndex == 3) {
entries.add(new PieEntry(45, mParties[0]));
entries.add(new PieEntry(55, mParties[1]));
colors.add(getResources().getColor(R.color.piecolor3));
colors.add(getResources().getColor(R.color.piecolor4));
} else {
entries.add(new PieEntry(60, mParties[0]));
entries.add(new PieEntry(40, mParties[1]));
colors.add(getResources().getColor(R.color.piecolor5));
colors.add(getResources().getColor(R.color.piecolor6));
}
colors.add(ColorTemplate.getHoloBlue());
dataSet.setColors(colors);
//dataSet.setSelectionShift(0f);
PieData data = new PieData(dataSet);
data.setValueFormatter(new PercentFormatter());
data.setValueTextSize(11f);
data.setValueTextColor(Color.BLACK);
data.setValueTypeface(mTfLight);
mChart.setData(data);
// undo all highlights
mChart.highlightValues(null);
mChart.invalidate();
}
}
//适配器
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return 4;
}
//这个方法用于显示标题
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "科目一";
case 1:
return "科目二";
case 2:
return "科目三";
case 3:
return "科目四";
}
return null;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.geekp.myapplication.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/appbar_padding_top"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/chart1"
android:layout_marginTop="100dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/tvXMax"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginBottom="15dp"
android:layout_marginRight="10dp"
android:gravity="right"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/tvYMax"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginBottom="15dp"
android:layout_marginRight="10dp"
android:gravity="right"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
源码传送门:http://xiazai.jb51.net/201612/yuanma/piechart-master(jb51.net).rar
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
来源:http://blog.csdn.net/gpwner/article/details/53744280


猜你喜欢
- 本文实例为大家分享了Unity调取移动端的麦克风进行录音并播放的具体代码,供大家参考,具体内容如下1.对MicroPhone类的理解对麦克风
- 本文实例为大家分享了Java实现简单万年历的具体代码,供大家参考,具体内容如下1 要求1、输入年份;2、输入月份;3、输出某年某月的日历。2
- 通常我们在看一些源码时,发现全是T、?,晕乎乎的:sob:。于是,把泛型掌握好十分重要!什么是泛型Java 泛型(generics)是 JD
- 使用版本:spring-boot: 2.1.6.RELEASEsping: 5.1.8.RELEASEjava: openjdk 11.0.
- 创建新的项目的时候,文件名一直追加,不分层对于刚用idea的小白,这个问题困扰了我好几天了,幸好现在还不怎么敲代码,下面给一个详细的解决方案
- FreeMarker 是一个采用 Java 开发的模版引擎,是一个基于模版生成文本的通用工具。 它被设计用来生成 HTML Web 页面,特
- ActiveMQ是Apache的一个开源项目,它是一个功能强劲的开源消息总线,也是一个中间件产品,它是JMS的一个实现。在介绍ActiveM
- 本篇概览在检测人脸数量、位置、性别、口罩等场景时,可以考虑使用百度开放平台提供的web接口,一个web请求就能完成检测得到结果,本篇记录了从
- 延迟加载1 使用延迟加载意义在进行数据查询时,为了提高数据库查询性能,尽量使用单表查询,因为单表查询比多表关联查询速度要快。如果查询单表就可
- 本文实例讲述了C#将Sql数据保存到Excel文件中的方法,非常有实用价值。分享给大家供大家参考借鉴之用。具体功能代码如下:public s
- Java的动态绑定所谓的动态绑定就是指程执行期间(而不是在编译期间)判断所引用对象的实际类型,根据其实际的类型调用其相应的方法。java继承
- 今天再学习一些C#的基础知识,如对 Int Array进行排序:你可以在控制台应用程序中,创建一个类别,它属性和2个构造函数:Source
- 简单看一下描述,例子最重要。1、getPath():返回定义时的路径,(就是你写什么路径,他就返回什么路径)2、getAbsolutePat
- VC和BCB中做一个Server的监听程序,只需要指定端口,然后监听(Listen)就行了.在C#找不到这个函数了,慢慢看MSDN,怎么需要
- 1. 运行环境 Enviroment当 MyBatis 与不同的应用结合时,需要不同的事务管理机制。与 Spring 结合时,由 Sprin
- 今天给大家带来一个向右滑动销毁Activity的效果,Activtiy随着手指的移动而移动,该效果在Android应用中还是比较少见的,在I
- 一、简述首先,Java 8引入了java.time.LocalDate来表示一个没有时间的日期。其次,使用Java 8版本,还需要更新jav
- Android UI 实现 * 详解listview 的使用步骤简单的listview * 实现1.实现效果图2.需要掌握的知识listvi
- 根据poi接收controller层的excel文件导入 可使用后缀
- 本文实例讲述了Android实现手机振动设置的方法。分享给大家供大家参考。具体如下:main.xml布局文件:<?xml versio