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

Android 天氣 App 實作:用 MPAndroidChart 畫出高低溫折線趨勢圖

編輯:關於 Android 程式設計

做天氣類應用時,幾乎一定會遇到一個需求:把一段時間內的氣溫變化畫成折線圖或曲線圖。這類圖表有個共同特徵——通常會並排出現兩條線,一條代表日最高溫,一條代表日最低溫。

先前我曾經介紹過 Android 平台上相當活躍的第三方圖表庫 MPAndroidChart(文章連結),有興趣的讀者可以點進去看它的基本用法。本文就直接在 MPAndroidChart 的基礎上,動手做一張氣溫高低溫折線圖。

一、主程式 MainActivity.java

package zhangphil.chart;

import java.text.DecimalFormat;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ValueFormatter;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LineChart mChart = (LineChart) findViewById(R.id.chart);
        setChart(mChart);
        // 產生 5 個資料點
        setData(mChart, 5);

        Legend l = mChart.getLegend();
        l.setForm(LegendForm.LINE);
        l.setTextSize(12f);
        l.setTextColor(Color.BLACK);
        l.setPosition(LegendPosition.BELOW_CHART_CENTER);

        XAxis xAxis = mChart.getXAxis();
        // 把 X 軸刻度移到底部
        xAxis.setPosition(XAxisPosition.BOTTOM);
        // X 軸標籤之間的間距
        xAxis.setSpaceBetweenLabels(1);
        xAxis.setTextSize(12f);
        xAxis.setTextColor(Color.BLACK);

        YAxis leftAxis = mChart.getAxisLeft();
        setYAxisLeft(leftAxis);
        YAxis rightAxis = mChart.getAxisRight();
        setYAxisRight(rightAxis);
    }

    private void setChart(LineChart mChart) {
        mChart.setDescription("https://blog.csdn.net/zhangphil");
        mChart.setNoDataTextDescription("如果傳入的資料是空的,你將看到這段文字。");
        mChart.setHighlightEnabled(true);
        mChart.setTouchEnabled(true);
        mChart.setDragDecelerationFrictionCoef(0.9f);
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        mChart.setDrawGridBackground(true);
        mChart.setHighlightPerDragEnabled(true);
        mChart.setPinchZoom(true);
        mChart.setBackgroundColor(Color.LTGRAY);
        mChart.animateX(3000);
    }

    private void setYAxisLeft(YAxis leftAxis) {
        // 左側 Y 軸標出 4 個刻度
        leftAxis.setLabelCount(4, true);
        leftAxis.setGridColor(Color.RED);
        leftAxis.setTextColor(Color.RED);
        leftAxis.setAxisMaxValue(50);
        leftAxis.setAxisMinValue(10);
        leftAxis.setStartAtZero(false);
        leftAxis.setDrawLabels(true);
    }

    private void setYAxisRight(YAxis rightAxis) {
        // 右側 Y 軸標出 8 個刻度
        rightAxis.setLabelCount(8, true);
        rightAxis.setTextColor(Color.BLUE);
        rightAxis.setGridColor(Color.BLUE);
        rightAxis.setAxisMaxValue(30);
        rightAxis.setAxisMinValue(-5);
        rightAxis.setStartAtZero(false);
        rightAxis.setDrawLabels(true);
    }

    private void setData(LineChart mChart, int count) {
        ArrayList<String> xVals = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            xVals.add("某月" + (i + 1) + "日");
        }

        ArrayList<Entry> yHigh = new ArrayList<Entry>();
        LineDataSet high = new LineDataSet(yHigh, "高溫");
        setHighTemperature(high, yHigh, count);

        ArrayList<Entry> yLow = new ArrayList<Entry>();
        LineDataSet low = new LineDataSet(yLow, "低溫");
        setLowTemperature(low, yLow, count);

        ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
        dataSets.add(high);
        dataSets.add(low);

        LineData data = new LineData(xVals, dataSets);
        data.setValueTextColor(Color.DKGRAY);
        data.setValueTextSize(10f);
        mChart.setData(data);
    }

    private void setHighTemperature(LineDataSet high, ArrayList<Entry> yVals, int count) {
        for (int i = 0; i < count; i++) {
            float val = (float) Math.random() + 30;
            yVals.add(new Entry(val, i));
        }
        // 以左側 Y 軸為準
        high.setAxisDependency(AxisDependency.LEFT);
        high.setLineWidth(5f);
        high.setColor(Color.RED);
        high.setCircleSize(8f);
        high.setCircleColor(Color.YELLOW);
        high.setCircleColorHole(Color.DKGRAY);
        high.setDrawCircleHole(true);
        // 自訂折線上數值的顯示格式,不設定時預設為 float 格式
        high.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                DecimalFormat decimalFormat = new DecimalFormat(".0");
                return "高溫" + decimalFormat.format(value);
            }
        });
    }

    private void setLowTemperature(LineDataSet low, ArrayList<Entry> yVals, int count) {
        for (int i = 0; i < count; i++) {
            float val = (float) Math.random() + 5;
            yVals.add(new Entry(val, i));
        }
        // 以右側 Y 軸為準
        low.setAxisDependency(AxisDependency.RIGHT);
        low.setColor(Color.GREEN);
        low.setLineWidth(3f);
        low.setCircleColor(Color.BLUE);
        low.setCircleColorHole(Color.LTGRAY);
        low.setCircleSize(5f);
        low.setDrawCircleHole(true);
        low.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                DecimalFormat decimalFormat = new DecimalFormat(".0");
                return "低溫" + decimalFormat.format(value);
            }
        });
    }
}

二、布局檔 activity_main.xml

布局非常單純,整個畫面就交給 LineChart 自己撐滿:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/chart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

執行結果如下:

三、務必搞懂 MPAndroidChart 的座標體系

很多人第一次用這個庫會踩的坑,就在 Y 軸上。MPAndroidChart 的縱座標軸其實有兩條:左縱軸(用 getAxisLeft() 取得)與右縱軸(用 getAxisRight() 取得)。

雖然它們在程式碼裡都是同一個 YAxis 類別,但實際使用時是各自獨立、互不干涉的,唯一共享的只有 X 橫軸。

回到本例:左邊那條紅色的 Y 軸對應高溫折線,有自己一套完整的繪製與縮放機制;右邊藍色的 Y 軸對應低溫折線,同樣有自己獨立的一套。兩條線各走各的座標系,千万不要混在一起理解,否則數值範圍一調整就會發現圖形完全跑掉。

實作上的關鍵就在 setAxisDependency(AxisDependency.LEFT / RIGHT)——它決定了一條資料線到底掛在哪一側的 Y 軸上。

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