Android工厂模式+View pager+MPAndroidChart实现的会旋转的饼状统计图

最近在做一个项目,由于有需要统计的需要,于是就做成了下面饼状统计图。
下图是效果图:
这里写图片描述

大致思路是:
这里写图片描述

关于的介绍这里不做详细介绍,如果想深入请点击开源项目MPAndroidChart
下面是其实现:

首先是添加MPAndroidChart依赖:
maven { url "https://jitpack.io" }
projectgradle

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>

需要源码的请移步我的个人github点击即可进入下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值