Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

基於 Android 的計步器(Pedometer)講解(二)——柱狀圖分析

編輯:關於 Android 程式設計

寫正文之前先小小吐槽一下:還有一個月就放假了,作業、考試、實習的種種考量擠在一起,加上基於 Hadoop 的數據分析馬上要驗收,最近真的忙得「外焦裡嫩」。目前定下的方向是 Android 開發,所以打算年後找一份 Android 實習,累積一些真正項目中的經驗。

廢話到此為止,進入正題。整個計步器項目已經上傳到 GitHub,感興趣的朋友可以過去看看(若能順手點顆星就更好啦)。

先來看兩張今天要實現的效果圖:

核心是自己實作了一個 HistogramView(柱狀圖)類,程式碼如下:

package com.example.histogram.widet;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

/**
 * 自訂的柱狀圖 View
 */
public class HistogramView extends View {
    private boolean Text = false;   // 是否在柱狀圖上顯示數字
    private int Height;             // 控件高度
    private int Width;              // 控件寬度
    private Bitmap bitmap;          // 柱狀圖的樣子
    private int mHeight;            // 柱狀圖高度
    private int AnimValue;          // 動畫插值
    private double Progress;
    private Canvas canvas;
    private HistogramAnimation ani;

    public void setText(boolean mText) {
        this.Text = mText;
        invalidate();
    }

    public HistogramView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        ani = new HistogramAnimation();
        ani.setDuration(1000);      // 動畫在 1 秒內完成
    }

    public HistogramView(Context context, AttributeSet attrs) {
        super(context, attrs);
        ani = new HistogramAnimation();
        ani.setDuration(1000);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Width = w;
        Height = h;
        mHeight = (int) (h * Progress * 0.9);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        this.canvas = canvas;
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(sp2px(getContext(), 12));
        paint.setColor(Color.parseColor("#6DCAEC"));

        RectF dst = new RectF(0, Height - AnimValue, Width, Height);
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.column);
        this.canvas.drawBitmap(bitmap, null, dst, paint);

        if (Text) {
            this.canvas.drawText((int) (Progress * 10000) + "", 0,
                    (Height - AnimValue) - 10, paint);
        }
    }

    /** 對外提供接口傳入數值 */
    public void setProgress(double Progress) {
        if (Progress < 0.03 && Progress != 0) {
            Progress = 0.03;
        }
        this.Progress = Progress;
        this.startAnimation(ani);
    }

    /** 自訂動畫類 */
    private class HistogramAnimation extends Animation {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            if (interpolatedTime < 1.0f) {
                AnimValue = (int) (mHeight * interpolatedTime);
            } else {
                AnimValue = mHeight;
            }
            postInvalidate();
        }
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}

FragmentAnalysis:分析七天步數的碎片

這個 Fragment 放七個 HistogramView 對應一週七天,底部顯示星期,上方顯示總步數與平均步數,並透過自訂動畫讓數字平滑遞增。點擊任一柱狀圖會切換該柱顯示具體數值。

public class FragmentAnalysis extends Fragment implements OnClickListener {
    private HistogramView hv1, hv2, hv3, hv4, hv5, hv6, hv7;  // 七個柱狀圖
    private TextView day1, day2, day3, day4, day5, day6, day7; // 一週七天
    private TextView average_step;  // 平均步數
    private TextView sum_step;      // 總步數
    private int sum = 0, sum1 = 0, average = 0, average1 = 0;
    private Calendar calendar;
    private View view;
    private AllAnimation ani;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.analysis, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        setWeek();
        setProgress();
        view.startAnimation(ani);
    }

    private void init() {
        average_step = (TextView) view.findViewById(R.id.average_step);
        sum_step = (TextView) view.findViewById(R.id.sum_step);
        ani = new AllAnimation();
        ani.setDuration(1000);
        calendar = Calendar.getInstance();

        hv1 = (HistogramView) view.findViewById(R.id.map1);
        hv2 = (HistogramView) view.findViewById(R.id.map2);
        hv3 = (HistogramView) view.findViewById(R.id.map3);
        hv4 = (HistogramView) view.findViewById(R.id.map4);
        hv5 = (HistogramView) view.findViewById(R.id.map5);
        hv6 = (HistogramView) view.findViewById(R.id.map6);
        hv7 = (HistogramView) view.findViewById(R.id.map7);
        hv1.setOnClickListener(this);
        hv2.setOnClickListener(this);
        hv3.setOnClickListener(this);
        hv4.setOnClickListener(this);
        hv5.setOnClickListener(this);
        hv6.setOnClickListener(this);
        hv7.setOnClickListener(this);

        day1 = (TextView) view.findViewById(R.id.Monday);
        day2 = (TextView) view.findViewById(R.id.Tuesday);
        day3 = (TextView) view.findViewById(R.id.Wednesday);
        day4 = (TextView) view.findViewById(R.id.Thursday);
        day5 = (TextView) view.findViewById(R.id.Friday);
        day6 = (TextView) view.findViewById(R.id.Saturday);
        day7 = (TextView) view.findViewById(R.id.Sunday);
    }

    @SuppressLint("SimpleDateFormat")
    private void setProgress() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        hv1.setProgress(5000 / 10000.0);  sum += 5000;  calendar.add(Calendar.DAY_OF_MONTH, -1);
        hv2.setProgress(3000 / 10000.0);  sum += 3000;  calendar.add(Calendar.DAY_OF_MONTH, -1);
        hv3.setProgress(2000 / 10000.0);  sum += 2000;  calendar.add(Calendar.DAY_OF_MONTH, -1);
        hv4.setProgress(7631 / 10000.0);  sum += 7631;  calendar.add(Calendar.DAY_OF_MONTH, -1);
        hv5.setProgress(4213 / 10000.0);  sum += 4213;  calendar.add(Calendar.DAY_OF_MONTH, -1);
        hv6.setProgress(8431 / 10000.0);  sum += 8431;  calendar.add(Calendar.DAY_OF_MONTH, -1);
        hv7.setProgress(9999 / 10000.0);  sum += 9999;
    }

    /** 依當天所在位置反推一週七天 */
    private void setWeek() {
        int day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        day1.setText(week(day));
        day2.setText(week(day - 1));
        day3.setText(week(day - 2));
        day4.setText(week(day - 3));
        day5.setText(week(day - 4));
        day6.setText(week(day - 5));
        day7.setText(week(day - 6));
    }

    @Override
    public void onClick(View arg0) {
        // 點擊某柱時只讓該柱顯示數字,其餘隱藏
        ...
    }

    /** 把數字星期轉為中文 */
    private String week(int day) {
        if (day < 1) { day += 7; }
        switch (day) {
            case 1: return "周一";
            case 2: return "周二";
            case 3: return "周三";
            case 4: return "周四";
            case 5: return "周五";
            case 6: return "周六";
            case 7: return "周日";
            default: return "";
        }
    }

    /** 數字遞增動畫 */
    private class AllAnimation extends Animation {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            if (interpolatedTime < 1.0f) {
                sum1 = (int) (sum * interpolatedTime);
                average1 = (int) (average * interpolatedTime);
            } else {
                sum1 = sum;
                average1 = average;
            }
            view.postInvalidate();
            sum_step.setText(sum1 + "");
            average = sum / 7;
            average_step.setText(average1 + "");
        }
    }
}

analysis.xml 布局

頂部為標題列,其下放總步數與平均步數兩個文字塊,中間橫向排列七個 HistogramView,底部標示一週七天並附一條基準線。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/analysis"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/analysis"
            android:textColor="#6DCAEC"
            android:textSize="20sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="10"
        android:orientation="horizontal">
        <com.example.histogram.widet.HistogramView
            android:id="@+id/map1"
            android:layout_width="30dp"
            android:layout_height="250dp"
            android:layout_gravity="bottom"
            android:layout_marginLeft="40dp"
            android:layout_marginTop="30dp" />
        <!-- map2 ~ map7 結構相同,僅 layout_marginLeft 改為 5dp -->
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">
        <TextView android:id="@+id/Monday"    android:layout_width="30dp" ... />
        <TextView android:id="@+id/Tuesday"   android:layout_width="30dp" ... />
        <TextView android:id="@+id/Wednesday" android:layout_width="30dp" ... />
        <TextView android:id="@+id/Thursday"  android:layout_width="30dp" ... />
        <TextView android:id="@+id/Friday"    android:layout_width="30dp" ... />
        <TextView android:id="@+id/Saturday"  android:layout_width="30dp" ... />
        <TextView android:id="@+id/Sunday"    android:layout_width="30dp" ... />
    </LinearLayout>
</LinearLayout>

如此一來,一個帶入場動畫、可點擊查看數值的七日步數柱狀圖就完成了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved