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,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),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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读8.8k次,点赞9次,收藏20次。本文操作环境:win10/Android studio 3.21.环境配置 在SDK Tools里选择 CMAKE/LLDB/NDK点击OK 安装这些插件. 2.创建CMakeLists.txt文件 在Project 目录下,右键app,点击新建File文件,命名为CMakeLists.txt点击OK,创建完毕! 3.配置文件 在CMa..._link c++ project with gradle
文章浏览阅读1.2w次,点赞15次,收藏69次。实现目的:由mainActivity界面跳转到otherActivity界面1.写好两个layout文件,activity_main.xml和otherxml.xmlactivity_main.xml&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;RelativeLayout ="http://schemas..._android studio 界面跳转
文章浏览阅读3.8w次。前言:最近在找Android上的全局代理软件来用,然后发现了这两款神作,都是外国的软件,而且都是开源的软件,因此把源码下载了下来,给有需要研究代理这方面的童鞋看看。不得不说,国外的开源精神十分浓,大家相互使用当前基础的开源软件,然后组合成一个更大更强的大开源软件。好吧,废话不多说,下面简单介绍一下这两款开源项目。一、ProxyDroid:ProxyDroid功能比较强大,用到的技术也比较多,源码也_proxydroid
文章浏览阅读2.5w次,点赞17次,收藏6次。创建项目后,运行项目时Gradle Build 窗口却显示错误:程序包R不存在通常情况下是不会出现这个错误的。我是怎么遇到这个错误的呢?第一次创建项目,company Domain我使用的是:aven.com,但是创建过程在卡在了Building 'Calculator' Gradle Project info这个过程中,于是我选择了“Cancel”第二次创建项目,我还是使用相同的项目名称和项目路_r不存在
文章浏览阅读8.9w次,点赞4次,收藏43次。前言:在Android上使用系统自带的代理,限制灰常大,仅支持系统自带的浏览器。这样像QQ、飞信、微博等这些单独的App都不能使用系统的代理。如何让所有软件都能正常代理呢?ProxyDroid这个软件能帮你解决!使用方法及步骤如下:一、推荐从Google Play下载ProxyDroid,目前最新版本是v2.6.6。二、对ProxyDroid进行配置(基本配置:) (1) Auto S_proxydroid使用教程
文章浏览阅读1.1w次,点赞4次,收藏17次。Android Studio提供了一个很实用的工具Android设备监视器(Android device monitor),该监视器中最常用的一个工具就是DDMS(Dalvik Debug Monitor Service),是 Android 开发环境中的Dalvik虚拟机调试监控服务。可以进行的操作有:为测试设备截屏,查看特定进程中正在运行的线程以及堆栈信息、Logcat、广播状态信息、模拟电话_安卓摄像头调试工具
文章浏览阅读2.1k次。初学Android游戏开发的朋友,往往会显得有些无所适从,他们常常不知道该从何处入手,每当遇到自己无法解决的难题时,又往往会一边羡慕于 iPhone下有诸如Cocos2d-iphone之类的免费游戏引擎可供使用,一边自暴自弃的抱怨Android平台游戏开发难度太高,又连个像样的游 戏引擎也没有,甚至误以为使用Java语言开发游戏是一件费力不讨好且没有出路的事情。事实上,这种想法完全是没有必_有素材的游戏引擎
文章浏览阅读3.2k次,点赞2次,收藏2次。2014年12月从csdn专家福利获得的一本书《Android游戏开发技术实战详解》,尘封了一年多的时间,今天才翻开来看。我认识中的Android,提到Android最先浮现在我脑海中的是那可爱的机器人图标:这个Logo是由Ascender公司设计的,诞生于2010年,其设计灵感源于男女厕所门上的图形符号(真的是灵感无处不在),于是布洛克绘制了一个简单的机器人,它的躯干就像锡罐的形状,头上还有两根_智能手机的特点有哪些?
文章浏览阅读8.1k次,点赞9次,收藏11次。首先,Android是不是真的找工作越来越难呢?这个可能是大家最关心的。这个受大的经济环境以及行业发展前景的影响,同时也和个人因素有关。2016-08-26近期一方面是所在的公司招聘Java开发人员很难招到合适的,投简历的人很少;而另一方面,经常听身边的人说Android、iOS方面找工作不好找,特别是没什么经验的,经验比较少的!说是不好找,但在我家所在的吉林省省会长春,会Unity3D+Maya_android 开发和asp.net哪个好 site:blog.csdn.net
文章浏览阅读6.1k次。在上篇“走进Android开发的世界,HelloWorld”,我们创建了一个Android 项目 HelloWorld,并演示了如何通过USB连接手机查看运行效果;而如果没有手机或没有对应型号的手机,又想做对应型号(屏幕尺寸、Android系统版本)的适配,应该怎么办呢?这时Android模拟器就派上用场了。Android模拟器Android SDK自带一个移动模拟器。它是一个可以运行在你电脑上的_安卓移动开发软件怎样预览
文章浏览阅读8.9k次。Google IO 2017 上宣布,将Kotlin语言作为安卓开发的官方语言。Kotlin由JetBrains公司开发,与Java 100%互通,并具备诸多Java尚不支持的新特性。谷歌称还将与JetBrains公司合作,为Kotlin设立一个非盈利基金会。Kotlin 是一个基于 JVM 的静态类型编程语言,Kotlin可以编译成Java字节码,也可以编译成JavaScript,方便在没有JV_kotlin为什么被嫌弃
文章浏览阅读9.6w次,点赞17次,收藏35次。有些情况下,不方便使用断点的方式来调试,而是希望在控制台打印输出日志,使用过Eclipse的同学都知道Java可以使用 System.out.println(""); 来在控制台打印输出日志,但是在android studio中却是不行的,还是有差别的,那应该用什么呢?android.util.Log在调试代码的时候我们需要查看调试信息,那我们就需要用Android Log类。android.ut_andirod.studio 为什么不在控制台打印输出
文章浏览阅读8.2k次,点赞2次,收藏8次。在上篇“走进Android开发的世界,HelloWorld”,我们创建了一个Android 项目 HelloWorld,并演示了如何通过USB连接手机查看运行效果;这里讲一下如何为应用添加一个按钮,并为按钮添加Click单击事件处理程序,显示/隐藏另一个按钮。添加按钮在HelloWorld项目的基础上,打开界面布局文件:activity_main.xml切换到Design(设计)模式;在组件But_activity_main.xml按钮隐藏
文章浏览阅读2.9k次,点赞3次,收藏9次。android 开发工具主流的还是Android Studio,当然也有很多人喜欢用Eclipse,也有人喜欢用IntelliJ IDEA ;还有Xamarin这种只需要编写一次代码,可以编译多种平台可运行的强大工具。但是它又真的强大吗?就我看来没有,身边很多人还是在用Android Studio、XCode开发应用,没见谁在用Xamarin之类的工具。系统要求WindowsMicrosoft®_android开发下载安装
文章浏览阅读4.2k次,点赞7次,收藏26次。你知道Hello World程序的由来吗?对于大多数编程语言的学习来说,真正入门的一课就是 Hello World!会而不难,难而不会。虽然很多人写过关于Android开发Hello World的文章,但随着时间的推移,开发工具、技术的进步,可能有些已经过时了。我就记录一下当下我所经历的第一个Android APP HelloWorld。一、准备1、开发环境参考:Android Studio 下载_android helloworld textview 句柄获取
这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方法有哪些的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Android...
这篇文章主要介绍“Android岛屿数量算法怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Android岛屿数量算...
本篇内容主要讲解“Android如何开发MQTT协议的模型及通信”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Andro...