Android creating Pie chart
Pie charts are used to describe information graphically, which is divided in slices to illustrate data in numerical proportion. They are used widely while giving informations in presentation, businesses and meetings.
So how to implement Pie chart in Android application? Well this small little post will giving some idea to make a good looking pie chart in Android. I hope you like this. I’m using library which I found from Github
Library Link on Github
I’m using Eclipse ADT. You can use Android studio to make this project. Go ahead and create a new project with :
Name : PieChartExample
Package declaration : com.example.piechartexample
Open already created (if not create it.) layout file res>layout>activity_main.xml and edit it as following :
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:orientation="vertical" > <LinearLayout android:id="@+id/lvparent" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:background="#ffffff" android:orientation="vertical" > <TextView android:id="@+id/txtheader" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="PET OWNERSHIP DATA" android:textColor="#1c1c1c" android:textSize="20sp" /> <view android:id="@+id/pie_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/txtheader" android:layout_centerHorizontal="true" android:layout_margin="5dp" class="com.example.piechartexample.PieView" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <LinearLayout android:id="@+id/lvOne" android:layout_width="20dp" android:layout_height="20dp" android:layout_gravity="center_vertical" android:layout_marginLeft="5dp" android:background="#000" android:orientation="horizontal" android:padding="2dp" /> <TextView android:id="@+id/txtOne" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="2dp" android:text="ONE" android:textColor="#000" android:textSize="20sp" /> <LinearLayout android:id="@+id/lvTwo" android:layout_width="20dp" android:layout_height="20dp" android:layout_gravity="center_vertical" android:layout_marginLeft="5dp" android:background="#000" android:orientation="horizontal" android:padding="2dp" /> <TextView android:id="@+id/txtTwo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="2dp" android:text="TWO" android:textColor="#000" android:textSize="20sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <LinearLayout android:id="@+id/lvThree" android:layout_width="20dp" android:layout_height="20dp" android:layout_gravity="center_vertical" android:layout_marginLeft="5dp" android:background="#000" android:orientation="horizontal" android:padding="2dp" /> <TextView android:id="@+id/txtThree" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="2dp" android:text="TWO" android:textColor="#000" android:textSize="20sp" /> <LinearLayout android:id="@+id/lvFour" android:layout_width="20dp" android:layout_height="20dp" android:layout_gravity="center_vertical" android:layout_marginLeft="5dp" android:background="#000" android:orientation="horizontal" android:padding="2dp" /> <TextView android:id="@+id/txtFour" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="2dp" android:text="TWO" android:textColor="#000" android:textSize="20sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <LinearLayout android:id="@+id/lvFive" android:layout_width="20dp" android:layout_height="20dp" android:layout_gravity="center_vertical" android:layout_marginLeft="5dp" android:background="#000" android:orientation="horizontal" android:padding="2dp" /> <TextView android:id="@+id/txtFive" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="2dp" android:text="TWO" android:textColor="#000" android:textSize="20sp" /> </LinearLayout> </LinearLayout> <TextView android:id="@+id/txtinfo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="2dp" android:padding="10dp" android:text="Pet ownership details" android:textColor="#000" android:textSize="20sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:orientation="horizontal" android:weightSum="2" > <Button android:id="@+id/btnundo" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="2dp" android:layout_weight="1" android:background="#1c1c1c" android:padding="5dp" android:text="Undo" android:textColor="#fff" android:textSize="20sp" /> <Button android:id="@+id/btnsave" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="2dp" android:layout_weight="1" android:background="#1c1c1c" android:padding="5dp" android:text="Save" android:textColor="#fff" android:textSize="20sp" /> </LinearLayout> </LinearLayout>
The view tag over here with id pie_view and with class com.example.piechartexample.PieView, will create the Pie chart.
The layout will look like below once you have created the whole application.
Create new class files with names :
- MyUtils.java
- PieHelper.java
- PieView.java
The above files are the library files which I got from the github library project for creating Graphs.
Edit MyUtils.java as following :
MyUtils.java:
package com.example.piechartexample; import android.content.Context; /** * Created by Dacer on 10/8/13. */ public class MyUtils { public static int dip2px(Context context, float dipValue){ final float scale = context.getResources().getDisplayMetrics().density; return (int)(dipValue * scale + 0.5f); } public static int px2dip(Context context, float pxValue){ final float scale = context.getResources().getDisplayMetrics().density; return (int)(pxValue / scale + 0.5f); } public static int sp2px(Context context, float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } }
Edit the PieHelper.java and edit it as following :
PieHelper.java:
package com.example.piechartexample; import android.graphics.Color; /** * Created by Dacer on 11/14/13. */ public class PieHelper { private float startDegree; private float endDegree; private float targetStartDegree; private float targetEndDegree; private String title; private int color; private float sweepDegree; int velocity = 5; /** * * @param percent * from 0 to 100 */ public PieHelper(float percent) { this(percent, null, 0); } public PieHelper(float percent, int color) { this(percent, null, color); } /** * * @param percent * from 0 to 100 * @param title */ PieHelper(float percent, String title) { this(percent, title, 0); } /** * * @param percent * from 0 to 100 * @param title * @param color */ public PieHelper(float percent, String title, int color) { this.sweepDegree = percent * 360 / 100; this.title = title; this.color = color; } PieHelper(float startDegree, float endDegree, PieHelper targetPie) { this.startDegree = startDegree; this.endDegree = endDegree; targetStartDegree = targetPie.getStartDegree(); targetEndDegree = targetPie.getEndDegree(); this.sweepDegree = targetPie.getSweep(); this.title = targetPie.getTitle(); this.color = targetPie.getColor(); } PieHelper setTarget(PieHelper targetPie) { this.targetStartDegree = targetPie.getStartDegree(); this.targetEndDegree = targetPie.getEndDegree(); this.title = targetPie.getTitle(); this.color = targetPie.getColor(); this.sweepDegree = targetPie.getSweep(); return this; } void setDegree(float startDegree, float endDegree) { this.startDegree = startDegree; this.endDegree = endDegree; } boolean isColorSetted() { return color != 0; } boolean isAtRest() { return (startDegree == targetStartDegree) && (endDegree == targetEndDegree); } void update() { this.startDegree = updateSelf(startDegree, targetStartDegree, velocity); this.endDegree = updateSelf(endDegree, targetEndDegree, velocity); this.sweepDegree = endDegree - startDegree; } String getPercentStr() { float percent = sweepDegree / 360 * 100; return String.valueOf((int) percent) + "%"; } public int getColor() { return color; } public String getTitle() { return title; } public float getSweep() { return sweepDegree; } public float getStartDegree() { return startDegree; } public float getEndDegree() { return endDegree; } private float updateSelf(float origin, float target, int velocity) { if (origin < target) { origin += velocity; } else if (origin > target) { origin -= velocity; } if (Math.abs(target - origin) < velocity) { origin = target; } return origin; } }
And lastly, edit the PieView.java as following :
PieView.java:
package com.example.piechartexample; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; /** * Created by Dacer on 9/26/14. */ public class PieView extends View { public interface OnPieClickListener{ void onPieClick(int index); } private Paint cirPaint; private Paint whiteLinePaint; private Point pieCenterPoint; private Paint textPaint; private RectF cirRect; private RectF cirSelectedRect; private int mViewWidth; private int mViewHeight; private int margin; private int pieRadius; private OnPieClickListener onPieClickListener; private ArrayList<PieHelper> pieHelperList; private int selectedIndex = NO_SELECTED_INDEX; private boolean showPercentLabel = true; public static final int NO_SELECTED_INDEX = -999; private final int[] DEFAULT_COLOR_LIST = {Color.parseColor("#33B5E5"), Color.parseColor("#AA66CC"), Color.parseColor("#99CC00"), Color.parseColor("#FFBB33"), Color.parseColor("#FF4444")}; private Runnable animator = new Runnable() { @Override public void run() { boolean needNewFrame = false; for(PieHelper pie : pieHelperList){ pie.update(); if(!pie.isAtRest()){ needNewFrame = true; } } if (needNewFrame) { postDelayed(this, 10); } invalidate(); } }; public PieView(Context context){ this(context,null); } public PieView(Context context, AttributeSet attrs){ super(context, attrs); pieHelperList = new ArrayList<PieHelper>(); cirPaint = new Paint(); cirPaint.setAntiAlias(true); cirPaint.setColor(Color.GRAY); whiteLinePaint = new Paint(cirPaint); whiteLinePaint.setColor(Color.WHITE); whiteLinePaint.setStrokeWidth(2f); textPaint = new Paint(); textPaint.setAntiAlias(true); textPaint.setColor(Color.WHITE); textPaint.setTextSize(MyUtils.sp2px(getContext(), 13)); textPaint.setStrokeWidth(5); textPaint.setTextAlign(Paint.Align.CENTER); pieCenterPoint = new Point(); cirRect = new RectF(); cirSelectedRect = new RectF(); } public void showPercentLabel(boolean show){ showPercentLabel = show; postInvalidate(); } public void setOnPieClickListener(OnPieClickListener listener){ onPieClickListener = listener; } public void setDate(ArrayList<PieHelper> helperList){ initPies(helperList); pieHelperList.clear(); removeSelectedPie(); if(helperList != null && !helperList.isEmpty()){ for(PieHelper pieHelper:helperList){ pieHelperList.add(new PieHelper(pieHelper.getStartDegree(),pieHelper.getStartDegree(),pieHelper)); } }else { pieHelperList.clear(); } removeCallbacks(animator); post(animator); // pieHelperList = helperList; // postInvalidate(); } /** * Set startDegree and endDegree for each PieHelper * @param helperList */ private void initPies(ArrayList<PieHelper> helperList){ float totalAngel = 270; for(PieHelper pie:helperList){ pie.setDegree(totalAngel, totalAngel + pie.getSweep()); totalAngel += pie.getSweep(); } } public void selectedPie(int index){ selectedIndex = index; if(onPieClickListener!=null) onPieClickListener.onPieClick(index); postInvalidate(); } public void removeSelectedPie(){ selectedIndex = NO_SELECTED_INDEX; if(onPieClickListener!=null) onPieClickListener.onPieClick(NO_SELECTED_INDEX); postInvalidate(); } @Override protected void onDraw(Canvas canvas) { if(pieHelperList.isEmpty()){ return ; } int index = 0; for(PieHelper pieHelper : pieHelperList){ boolean selected = (selectedIndex == index); RectF rect = selected? cirSelectedRect: cirRect; if(pieHelper.isColorSetted()){ cirPaint.setColor(pieHelper.getColor()); }else { cirPaint.setColor(DEFAULT_COLOR_LIST[index%5]); } canvas.drawArc(rect, pieHelper.getStartDegree(), pieHelper.getSweep(), true, cirPaint); drawPercentText(canvas, pieHelper); drawLineBesideCir(canvas, pieHelper.getStartDegree(), selected); drawLineBesideCir(canvas, pieHelper.getEndDegree(), selected); index++; } } private void drawLineBesideCir(Canvas canvas, float angel, boolean selectedCir){ int sth2 = selectedCir? mViewHeight/2 : pieRadius; // Sorry I'm really don't know how to name the variable.. int sth = 1; // And it's if(angel%360 > 180 && angel%360 < 360){ sth = -1; } float lineToX = (float)(mViewHeight/2 + Math.cos(Math.toRadians(-angel)) * sth2); float lineToY = (float)(mViewHeight/2 + sth * Math.abs(Math.sin(Math.toRadians(-angel))) * sth2); canvas.drawLine(pieCenterPoint.x, pieCenterPoint.y, lineToX, lineToY, whiteLinePaint); } private void drawPercentText(Canvas canvas, PieHelper pieHelper){ if(!showPercentLabel) return ; float angel = (pieHelper.getStartDegree() + pieHelper.getEndDegree()) /2; int sth = 1; if(angel%360 > 180 && angel%360 < 360){ sth = -1; } float x = (float)(mViewHeight/2 + Math.cos(Math.toRadians(-angel)) * pieRadius/2); float y = (float)(mViewHeight/2 + sth * Math.abs(Math.sin(Math.toRadians(-angel))) * pieRadius/2); canvas.drawText(pieHelper.getPercentStr(), x, y, textPaint); } private void drawText(Canvas canvas, PieHelper pieHelper){ if(pieHelper.getTitle() == null) return ; float angel = (pieHelper.getStartDegree() + pieHelper.getEndDegree()) /2; int sth = 1; if(angel%360 > 180 && angel%360 < 360){ sth = -1; } float x = (float)(mViewHeight/2 + Math.cos(Math.toRadians(-angel)) * pieRadius/2); float y = (float)(mViewHeight/2 + sth * Math.abs(Math.sin(Math.toRadians(-angel))) * pieRadius/2); canvas.drawText(pieHelper.getTitle(), x, y, textPaint); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN ||event.getAction() == MotionEvent.ACTION_MOVE){ selectedIndex = findPointAt((int) event.getX(), (int) event.getY()); if(onPieClickListener != null){ onPieClickListener.onPieClick(selectedIndex); } postInvalidate(); } return true; } /** * find pie index where point is * @param x * @param y * @return */ private int findPointAt(int x, int y){ double degree = Math.atan2(x-pieCenterPoint.x, y-pieCenterPoint.y)* 180 / Math.PI; degree = -(degree-180) + 270; int index = 0; for(PieHelper pieHelper:pieHelperList){ if(degree>=pieHelper.getStartDegree() && degree<=pieHelper.getEndDegree()){ return index; } index++; } return NO_SELECTED_INDEX; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mViewWidth = measureWidth(widthMeasureSpec); mViewHeight = measureHeight(heightMeasureSpec); margin = mViewWidth/16; pieRadius = (mViewWidth)/2-margin; pieCenterPoint.set(pieRadius+margin, pieRadius+margin); cirRect.set(pieCenterPoint.x-pieRadius, pieCenterPoint.y-pieRadius, pieCenterPoint.x+pieRadius, pieCenterPoint.y+pieRadius); cirSelectedRect.set(2, //minor margin for bigger circle 2, mViewWidth-2, mViewHeight-2); setMeasuredDimension(mViewWidth, mViewHeight); } private int measureWidth(int measureSpec){ int preferred = 3; return getMeasurement(measureSpec, preferred); } private int measureHeight(int measureSpec){ int preferred = mViewWidth; return getMeasurement(measureSpec, preferred); } private int getMeasurement(int measureSpec, int preferred){ int specSize = View.MeasureSpec.getSize(measureSpec); int measurement; switch(View.MeasureSpec.getMode(measureSpec)){ case View.MeasureSpec.EXACTLY: measurement = specSize; break; case View.MeasureSpec.AT_MOST: measurement = Math.min(preferred, specSize); break; default: measurement = preferred; break; } return measurement; } }
And this completes the library files.
So, its time for the MainActivity.java class file.
In your MainActivity.java class file declare following variables.
private TextView txtinfo; LinearLayout lvOne, lvTwo, lvThree, lvFour, lvFive, lvparent; TextView txtOne, txtTwo, txtThree, txtFour, txtFive; Button btnundo, btnsave; PieView pieView; Uri outputFileUri; OutputStream outStream = null; String[] petNames = new String[] { "Dogs", "Cats", "Fish", "Rabbits", "Roddents" }; int[] percentage = new int[] { 55, 25, 10, 5, 5 };
In the onCreate method write the following lines.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtinfo = (TextView) findViewById(R.id.txtinfo); pieView = (PieView) findViewById(R.id.pie_view); lvOne = (LinearLayout) findViewById(R.id.lvOne); lvTwo = (LinearLayout) findViewById(R.id.lvTwo); lvThree = (LinearLayout) findViewById(R.id.lvThree); lvFour = (LinearLayout) findViewById(R.id.lvFour); lvFive = (LinearLayout) findViewById(R.id.lvFive); lvparent = (LinearLayout) findViewById(R.id.lvparent); txtOne = (TextView) findViewById(R.id.txtOne); txtTwo = (TextView) findViewById(R.id.txtTwo); txtThree = (TextView) findViewById(R.id.txtThree); txtFour = (TextView) findViewById(R.id.txtFour); txtFive = (TextView) findViewById(R.id.txtFive); btnundo = (Button) findViewById(R.id.btnundo); btnsave = (Button) findViewById(R.id.btnsave);
Now we will create two methods for Creating the Pie chart and Saving the Pie chart in the Phone memory in Image format.
First for saving the image in Image format. Create a method named SaveImage().
public void SaveImage() { lvparent.buildDrawingCache(); Bitmap bm = lvparent.getDrawingCache(); try { File root = new File(Environment.getExternalStorageDirectory() + File.separator + "PieChartsExample" + File.separator); root.mkdirs(); File sdImageMainDirectory = new File(root, "piechart.jpg"); outputFileUri = Uri.fromFile(sdImageMainDirectory); outStream = new FileOutputStream(sdImageMainDirectory); } catch (Exception e) { Toast.makeText(this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show(); } try { bm.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); outStream.close(); Toast.makeText(this, "Created successfully!", Toast.LENGTH_SHORT) .show(); } catch (Exception e) { } }
This method will be saving the Pie chart in the internal memory of the Phone.
Now create following method to create the Pie chart view.
private void set(PieView pieView) { ArrayList<PieHelper> pieHelperArrayList = new ArrayList<PieHelper>(); int color0 = Color.rgb(0, 128, 255); int color1 = Color.rgb(252, 3, 71); int color2 = Color.rgb(117, 91, 4); int color3 = Color.rgb(3, 7, 173); int color4 = Color.rgb(20, 156, 82); pieHelperArrayList.add(new PieHelper(55, color0)); pieHelperArrayList.add(new PieHelper(25, color1)); pieHelperArrayList.add(new PieHelper(10, color2)); pieHelperArrayList.add(new PieHelper(5, color3)); pieHelperArrayList.add(new PieHelper(5, color4)); lvOne.setBackgroundColor(color0); txtOne.setText(petNames[0].toString()); lvTwo.setBackgroundColor(color1); txtTwo.setText(petNames[1]); lvThree.setBackgroundColor(color2); txtThree.setText(petNames[2]); lvFour.setBackgroundColor(color3); txtFour.setText(petNames[3]); lvFive.setBackgroundColor(color4); txtFive.setText(petNames[4]); pieView.setDate(pieHelperArrayList); pieView.setOnPieClickListener(new PieView.OnPieClickListener() { @Override public void onPieClick(int index) { if (index != PieView.NO_SELECTED_INDEX) { txtinfo.setText(percentage[index] + "% owns " + petNames[index] + "."); } else { txtinfo.setText("No selected pie"); } } }); }
And call this method in the onCreate method after declaration of all the variables.
Here’s the full activity.
MainActivity.java:
package com.example.piechartexample; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private TextView txtinfo; LinearLayout lvOne, lvTwo, lvThree, lvFour, lvFive, lvparent; TextView txtOne, txtTwo, txtThree, txtFour, txtFive; Button btnundo, btnsave; PieView pieView; Uri outputFileUri; OutputStream outStream = null; String[] petNames = new String[] { "Dogs", "Cats", "Fish", "Rabbits", "Roddents" }; int[] percentage = new int[] { 55, 25, 10, 5, 5 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtinfo = (TextView) findViewById(R.id.txtinfo); pieView = (PieView) findViewById(R.id.pie_view); lvOne = (LinearLayout) findViewById(R.id.lvOne); lvTwo = (LinearLayout) findViewById(R.id.lvTwo); lvThree = (LinearLayout) findViewById(R.id.lvThree); lvFour = (LinearLayout) findViewById(R.id.lvFour); lvFive = (LinearLayout) findViewById(R.id.lvFive); lvparent = (LinearLayout) findViewById(R.id.lvparent); txtOne = (TextView) findViewById(R.id.txtOne); txtTwo = (TextView) findViewById(R.id.txtTwo); txtThree = (TextView) findViewById(R.id.txtThree); txtFour = (TextView) findViewById(R.id.txtFour); txtFive = (TextView) findViewById(R.id.txtFive); btnundo = (Button) findViewById(R.id.btnundo); btnsave = (Button) findViewById(R.id.btnsave); btnsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SaveImage(); } }); btnundo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub pieView.removeSelectedPie(); txtinfo.setText("Pet ownership details"); } }); set(pieView); } public void SaveImage() { lvparent.buildDrawingCache(); Bitmap bm = lvparent.getDrawingCache(); try { File root = new File(Environment.getExternalStorageDirectory() + File.separator + "PieChartsExample" + File.separator); root.mkdirs(); File sdImageMainDirectory = new File(root, "piechart.jpg"); outputFileUri = Uri.fromFile(sdImageMainDirectory); outStream = new FileOutputStream(sdImageMainDirectory); } catch (Exception e) { Toast.makeText(this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show(); } try { bm.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); outStream.close(); Toast.makeText(this, "Created successfully!", Toast.LENGTH_SHORT) .show(); } catch (Exception e) { } } private void set(PieView pieView) { ArrayList<PieHelper> pieHelperArrayList = new ArrayList<PieHelper>(); int color0 = Color.rgb(0, 128, 255); int color1 = Color.rgb(252, 3, 71); int color2 = Color.rgb(117, 91, 4); int color3 = Color.rgb(3, 7, 173); int color4 = Color.rgb(20, 156, 82); pieHelperArrayList.add(new PieHelper(55, color0)); pieHelperArrayList.add(new PieHelper(25, color1)); pieHelperArrayList.add(new PieHelper(10, color2)); pieHelperArrayList.add(new PieHelper(5, color3)); pieHelperArrayList.add(new PieHelper(5, color4)); lvOne.setBackgroundColor(color0); txtOne.setText(petNames[0].toString()); lvTwo.setBackgroundColor(color1); txtTwo.setText(petNames[1]); lvThree.setBackgroundColor(color2); txtThree.setText(petNames[2]); lvFour.setBackgroundColor(color3); txtFour.setText(petNames[3]); lvFive.setBackgroundColor(color4); txtFive.setText(petNames[4]); pieView.setDate(pieHelperArrayList); pieView.setOnPieClickListener(new PieView.OnPieClickListener() { @Override public void onPieClick(int index) { if (index != PieView.NO_SELECTED_INDEX) { txtinfo.setText(percentage[index] + "% owns " + petNames[index] + "."); } else { txtinfo.setText("No selected pie"); } } }); } }
AndroidManisfest.xml file :
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.piechartexample" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
And that’s all friends. Your Pie chart is ready.
Please do comment and share this code to help your friends and others.