欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-02-26 22:24:10
android 实现会旋转的饼状统计图实例代码 最近在做一个项目,由于有需要统计的需要,于是就做成了下面饼状统计图。 下图是效果图: 大致思路是:...

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>

源码传送门:

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!