Android 实现会旋转的饼状统计图实例代码

作者:lqh 时间:2022-04-08 09:38:50 

Android 实现会旋转的饼状统计图实例代码

最近在做一个项目,由于有需要统计的需要,于是就做成了下面饼状统计图。

下图是效果图:

Android 实现会旋转的饼状统计图实例代码

大致思路是:

Android 实现会旋转的饼状统计图实例代码

关于的介绍这里不做详细介绍,如果想深入请点击开源项目MPAndroidChart

下面是其实现:

首先是添加MPAndroidChart依赖:


maven { url "https://jitpack.io" }

Android 实现会旋转的饼状统计图实例代码


compile 'com.github.PhilJay:MPAndroidChart:v3.0.1'

Android 实现会旋转的饼状统计图实例代码

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

标签:Android,饼状,统计图
0
投稿

猜你喜欢

  • Java实战之实现一个好用的MybatisPlus代码生成器

    2023-06-18 02:16:10
  • Java Scanner类用法及nextLine()产生的换行符问题实例分析

    2022-12-22 21:44:04
  • java list,set,map,数组间的相互转换详解

    2023-04-11 13:02:04
  • Android RecyclerView的卡顿问题的解决方法

    2023-07-01 20:01:14
  • 布隆过滤器(Bloom Filter)的Java实现方法

    2022-09-14 18:06:06
  • TextBox获取输入焦点时自动全选的实现方法

    2022-01-01 02:22:49
  • java实现五子棋程序

    2022-01-29 10:40:38
  • Java由浅入深带你精通继承super

    2023-11-23 02:34:28
  • IDEA2020.2.3中创建JavaWeb工程的完整步骤记录

    2022-03-15 05:16:02
  • Android Handler机制详解原理

    2023-10-29 22:03:44
  • springboot搭建访客管理系统的实现示例

    2023-09-02 13:10:41
  • 防止未登录用户操作—基于struts2拦截器的简单实现

    2021-06-11 13:21:00
  • C#语言主要特性总结

    2021-07-16 07:59:43
  • C#控件Picturebox实现鼠标拖拽功能

    2021-10-30 20:52:36
  • SpringCloud Gateway HttpWebHandlerAdapter链路调用请求流程介绍

    2023-04-29 00:12:18
  • Java中线程安全问题

    2021-12-02 05:51:59
  • Android设置PreferenceCategory背景颜色的方法

    2021-09-24 10:13:29
  • Android自定义控件ViewGroup实现标签云(四)

    2021-11-30 14:58:36
  • Java Vector实现班级信息管理系统

    2023-11-25 03:09:09
  • 浅谈Java面向接口编程

    2021-07-25 16:29:58
  • asp之家 软件编程 m.aspxhome.com