• Tutorials
  • Tips & Tricks
  • Applications
  • News

Android Trainee

  • Tutorials
  • Tips & Tricks
  • Applications
  • News
Home  /  Tutorials  /  Draw Android Bar Chart With Animation.
14 July 2015

Draw Android Bar Chart With Animation.

Written by admin@androidtrainee
Tutorials android bar chart, Animation Bar Chart, Anroid Chart Animation, Bar Chart, chart, chartview Leave a Comment

Draw Android Bar Chart With Animation.

 

—>  AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.barchart"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="22" />

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

 

IN Layout Folder

activity_main.xml

 


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#ffffff">

<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/horizontalScrollView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<view
android:layout_width="wrap_content"
android:layout_height="300dp"
class="com.example.barchart.BarView"
android:id="@+id/bar_view" />
</HorizontalScrollView>



<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Random"
android:id="@+id/bar_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

 

MyUtils.java

 


package com.example.barchart;


import android.content.Context;


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);
}

}

 

MainActivity.java


package com.example.barchart;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {
BarView barView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
barView = (BarView)findViewById(R.id.bar_view);
button = (Button)findViewById(R.id.bar_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
randomSet(barView);
}
});
randomSet(barView);
}
private void randomSet(BarView barView){
int random = (int)(Math.random()*20)+6;
ArrayList<String> test = new ArrayList<String>();
for (int i=0; i<random; i++){
test.add("test");
test.add("pqg");
//            test.add(String.valueOf(i+1));
}
barView.setBottomTextList(test);

ArrayList<Integer> barDataList = new ArrayList<Integer>();
for(int i=0; i<random*2; i++){
barDataList.add((int)(Math.random() * 100));
}
barView.setDataList(barDataList,100);
}

}

BarView.java


package com.example.barchart;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AnimationUtils;

import java.util.ArrayList;


public class BarView extends View {
private ArrayList<Float> percentList;
private ArrayList<Float> targetPercentList;
private Paint textPaint;
private Paint bgPaint;
private Paint fgPaint;
private Rect rect;
private int barWidth;
//    private boolean showSideMargin = true;
private int bottomTextDescent;
private boolean autoSetWidth = true;
private int topMargin;
private int bottomTextHeight;
private ArrayList<String> bottomTextList = new ArrayList<String>();
private final int MINI_BAR_WIDTH;
private final int BAR_SIDE_MARGIN;
private final int TEXT_TOP_MARGIN;
private final int TEXT_COLOR = Color.parseColor("#9B9A9B");
private final int BACKGROUND_COLOR = Color.parseColor("#F6F6F6");
private final int FOREGROUND_COLOR = Color.parseColor("#FC496D");

private Runnable animator = new Runnable() {
@Override
public void run() {
boolean needNewFrame = false;
for (int i=0; i<targetPercentList.size();i++) {
if (percentList.get(i) < targetPercentList.get(i)) {
percentList.set(i,percentList.get(i)+0.02f);
needNewFrame = true;
} else if (percentList.get(i) > targetPercentList.get(i)){
percentList.set(i,percentList.get(i)-0.02f);
needNewFrame = true;
}
if(Math.abs(targetPercentList.get(i)-percentList.get(i))<0.02f){
percentList.set(i,targetPercentList.get(i));
}
}
if (needNewFrame) {
postDelayed(this, 20);
}
invalidate();
}
};

public BarView(Context context){
this(context,null);
}
public BarView(Context context, AttributeSet attrs){
super(context, attrs);
bgPaint = new Paint();
bgPaint.setAntiAlias(true);
bgPaint.setColor(BACKGROUND_COLOR);
fgPaint = new Paint(bgPaint);
fgPaint.setColor(FOREGROUND_COLOR);
rect = new Rect();
topMargin = MyUtils.dip2px(context, 5);
int textSize = MyUtils.sp2px(context, 15);
barWidth = MyUtils.dip2px(context,22);
MINI_BAR_WIDTH = MyUtils.dip2px(context,22);
BAR_SIDE_MARGIN  = MyUtils.dip2px(context,22);
TEXT_TOP_MARGIN = MyUtils.dip2px(context, 5);
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(TEXT_COLOR);
textPaint.setTextSize(textSize);
textPaint.setTextAlign(Paint.Align.CENTER);
percentList = new ArrayList<Float>();
}

/**
* dataList will be reset when called is method.
* @param bottomStringList The String ArrayList in the bottom.
*/
public void setBottomTextList(ArrayList<String> bottomStringList){
//        this.dataList = null;
this.bottomTextList = bottomStringList;
Rect r = new Rect();
bottomTextDescent = 0;
barWidth = MINI_BAR_WIDTH;
for(String s:bottomTextList){
textPaint.getTextBounds(s,0,s.length(),r);
if(bottomTextHeight<r.height()){
bottomTextHeight = r.height();
}
if(autoSetWidth&&(barWidth<r.width())){
barWidth = r.width();
}
if(bottomTextDescent<(Math.abs(r.bottom))){
bottomTextDescent = Math.abs(r.bottom);
}
}
setMinimumWidth(2);
postInvalidate();
}

/**
*
* @param list The ArrayList of Integer with the range of [0-max].
*/
public void setDataList(ArrayList<Integer> list, int max){
targetPercentList = new ArrayList<Float>();
if(max == 0) max = 1;

for(Integer integer : list){
targetPercentList.add(1-(float)integer/(float)max);
}

// Make sure percentList.size() == targetPercentList.size()
if(percentList.isEmpty() || percentList.size()<targetPercentList.size()){
int temp = targetPercentList.size()-percentList.size();
for(int i=0; i<temp;i++){
percentList.add(1f);
}
} else if (percentList.size()>targetPercentList.size()){
int temp = percentList.size()-targetPercentList.size();
for(int i=0; i<temp;i++){
percentList.remove(percentList.size()-1);
}
}
setMinimumWidth(2);
removeCallbacks(animator);
post(animator);
}

@Override
protected void onDraw(Canvas canvas) {
int i = 1;
if(percentList != null && !percentList.isEmpty()){
for(Float f:percentList){
rect.set(BAR_SIDE_MARGIN*i+barWidth*(i-1),
topMargin,
(BAR_SIDE_MARGIN+barWidth)* i,
getHeight()-bottomTextHeight-TEXT_TOP_MARGIN);
canvas.drawRect(rect,bgPaint);

rect.set(BAR_SIDE_MARGIN*i+barWidth*(i-1),
topMargin+(int)((getHeight()-topMargin-bottomTextHeight-TEXT_TOP_MARGIN)*percentList.get(i-1)),
(BAR_SIDE_MARGIN+barWidth)* i,
getHeight()-bottomTextHeight-TEXT_TOP_MARGIN);
canvas.drawRect(rect,fgPaint);
i++;
}
}

if(bottomTextList != null && !bottomTextList.isEmpty()){
i = 1;
for(String s:bottomTextList){
canvas.drawText(s,BAR_SIDE_MARGIN*i+barWidth*(i-1)+barWidth/2,
getHeight()-bottomTextDescent,textPaint);
i++;
}
}
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mViewWidth = measureWidth(widthMeasureSpec);
int mViewHeight = measureHeight(heightMeasureSpec);
setMeasuredDimension(mViewWidth,mViewHeight);
}

private int measureWidth(int measureSpec){
int preferred = 0;
if(bottomTextList != null){
preferred = bottomTextList.size()*(barWidth+BAR_SIDE_MARGIN);
}
return getMeasurement(measureSpec, preferred);
}

private int measureHeight(int measureSpec){
int preferred = 222;
return getMeasurement(measureSpec, preferred);
}

private int getMeasurement(int measureSpec, int preferred){
int specSize = MeasureSpec.getSize(measureSpec);
int measurement;
switch(MeasureSpec.getMode(measureSpec)){
case MeasureSpec.EXACTLY:
measurement = specSize;
break;
case MeasureSpec.AT_MOST:
measurement = Math.min(preferred, specSize);
break;
default:
measurement = preferred;
break;
}
return measurement;
}

}

 

admin@androidtrainee

 Previous Article Draw Android Clock Pie Chart With Animation.
Next Article   Android Staggered Grid & List View.

Related Posts

  • Android New Quick Action Animation.

    July 15, 2015
  • Android satellite menu Animation.

    July 15, 2015
  • Android Staggered Grid & List View.

    July 14, 2015

Leave a Reply

Cancel reply

Tags

admob Advertising Networks AerServ Airpush android android ads android Advertising Networks Android App android chart animation Android GridView android L android lollipop androidmapv2 AppBrain AppFlood Appia AppKey Appnext AppOptim Appwiz chart chartview Epom Market google place api GridView Image Loader InMobi LeadBolt location map mapv2 mapv2 api material design Minimob Mobicow MobileCore MobiMicro NativeX Pingjam RevMob StarApplication startapp TapContext touched location Widdit

Count per Day

  • 347Reads yesterday:
  • 463794Total visitors:
  • 14Visitors today:
  • 2387Visitors per month:
  • 0Visitors currently online:
© Copyright 2014. Theme by BloomPixel.
Posting....