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

MPAndroidChart 使用技巧:折線圖與樣式封裝

編輯:關於 Android 程式設計

前言

由於之前項目中用到圖表的次數不少,若全靠手繪不僅費時,效果也未必達標。網上關於圖表的開源「輪子」很豐富,於是決定找一個來熟練運用,方便以後隨取隨用。

在 GitHub 上搜索 Android Charts 會列出大量項目。最初我嘗試了 hellocharts-android,折騰一兩天後發現最終效果與預期有落差,於是改用本文的主角——MPAndroidChart。(這也提醒我們:如何挑選合適的開源資源本身就是一門學問,選錯了可是白白浪費時間。)

獲取依賴

一般我們會直接在 app 模塊的 build.gradle 裡 compile 引用。但這次我選擇把源碼下載下來,將 MPChartLib 導入項目(並改名為 JNChartLib,因為我在其中做了一些簡單封裝),方便以後直接複用。

導入方式:File → New → Import Module,選擇 JNChartLib;然後在 setting.gradle 中加入 include ':JNChartLib',並在 app 的 build.gradle 中加入 compile project(':JNChartLib')。

圖表控件(以折線圖為例)

本案例的基礎布局採用 RadioButton + Fragment 實現底部導航,圖表控件放在 Fragment 布局上:

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

    <com.jn.chart.charts.LineChart
        android:id="@+id/lineChart"
        android:layout_width="match_parent"
        android:layout_height="300dp" />
</LinearLayout>

在 Fragment 中初始化圖表並設置數據:

public class Fragment1 extends Fragment {
    private LineChart mLineChart;
    private Context context;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment1_layout, container, false);
        this.context = getActivity();
        mLineChart = view.findViewById(R.id.lineChart);
        mLineChart.setDescription("全省移網");

        ArrayList<String> xValues = new ArrayList<>();
        for (int i = 0; i < 15; i++) xValues.add("" + i);

        ArrayList<Entry> yValue = new ArrayList<>();
        yValue.add(new Entry(13, 1));
        yValue.add(new Entry(6, 2));
        yValue.add(new Entry(3, 3));
        // ...

        LineChartManager.setLineName("當月值");

        ArrayList<Entry> yValue1 = new ArrayList<>();
        yValue1.add(new Entry(17, 1));
        yValue1.add(new Entry(3, 2));
        // ...
        LineChartManager.setLineName1("上月值");

        LineChartManager.initDoubleLineChart(context, mLineChart, xValues, yValue, yValue1);
        return view;
    }
}

代碼中的 LineChartManager 是我封裝的圖表創建、樣式與坐標軸配置類,這樣在 Activity 或 Fragment 中只需設置好數據與描述即可,無須關心其他屬性。若想把圖表定制成想要的樣子,直接改這個封裝類即可。

public class LineChartManager {
    private static String lineName = null;
    private static String lineName1 = null;

    /** 創建單條折線 */
    public static void initSingleLineChart(Context context, LineChart mLineChart,
                                           ArrayList<String> xValues, ArrayList<Entry> yValue) {
        initDataStyle(context, mLineChart);
        LineDataSet dataSet = new LineDataSet(yValue, lineName);
        dataSet.setColor(Color.RED);
        dataSet.setCircleColor(Color.RED);
        dataSet.setDrawValues(false);
        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(dataSet);
        mLineChart.setData(new LineData(xValues, dataSets));
        mLineChart.animateY(2000, Easing.EasingOption.Linear);
        mLineChart.animateX(2000, Easing.EasingOption.Linear);
        mLineChart.invalidate();
    }

    /** 創建兩條折線 */
    public static void initDoubleLineChart(Context context, LineChart mLineChart,
                                           ArrayList<String> xValues,
                                           ArrayList<Entry> yValue, ArrayList<Entry> yValue1) {
        initDataStyle(context, mLineChart);
        LineDataSet dataSet = new LineDataSet(yValue, lineName);
        dataSet.setColor(Color.RED);
        dataSet.setCircleColor(Color.RED);
        dataSet.setDrawValues(false);

        LineDataSet dataSet1 = new LineDataSet(yValue1, lineName1);
        dataSet1.enableDashedLine(10f, 10f, 0f); // 設為虛線
        dataSet1.setColor(Color.parseColor("#66CDAA"));
        dataSet1.setCircleColor(Color.parseColor("#66CDAA"));
        dataSet1.setDrawValues(false);

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(dataSet);
        dataSets.add(dataSet1);
        mLineChart.setData(new LineData(xValues, dataSets));
        mLineChart.animateY(2000, Easing.EasingOption.Linear);
        mLineChart.animateX(2000, Easing.EasingOption.Linear);
        mLineChart.invalidate();
    }

    /** 初始化圖表樣式 */
    private static void initDataStyle(Context context, LineChart mLineChart) {
        mLineChart.setTouchEnabled(true);
        mLineChart.setScaleEnabled(false);

        Legend legend = mLineChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);

        XAxis xAxis = mLineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisLineColor(Color.parseColor("#66CDAA"));
        xAxis.setAxisLineWidth(5);
        xAxis.setDrawGridLines(false);
        xAxis.setEnabled(true);

        YAxis yAxisLeft = mLineChart.getAxisLeft();
        yAxisLeft.setAxisLineColor(Color.parseColor("#66CDAA"));
        yAxisLeft.setAxisLineWidth(5);
        yAxisLeft.setDrawGridLines(false);

        mLineChart.getAxisRight().setEnabled(false);
    }

    public static void setLineName(String name) { lineName = name; }
    public static void setLineName1(String name) { lineName1 = name; }
}

備注

本案例只封裝了折線圖、柱狀圖與折線柱狀混合圖三種。柱狀圖封裝在 BarChartManager,混合圖封裝在 CombinedChartManager,用法與折線圖類似,具體可到 GitHub 直接 clone 參考。

我還重寫了 MarkerView 類,讓點擊折線點或柱狀圖時彈出顯示數值的視圖。使用時需單獨建立一個只含 TextView 的布局,再在對應管理類中調用:

MyMakerView mv = new MyMakerView(context, R.layout.item_mark_layout);
mLineChart.setMarkerView(mv);

API 與資源

完整的 API 文檔可參考:

  • https://jitpack.io/com/github/PhilJay/MPAndroidChart/v3.0.0-beta1/javadoc/
  • 簡潔版示例(繁體):https://github.com/25sprout/ChartLib-Demo-Android

案例代碼 GitHub 地址:JNChartDemo。

效果圖:

透過把樣式配置集中到一個 Manager 類中,我們在業務層只需關注「數據從哪來、圖表長什麼大致形態」,極大提升了開發效率與可維護性。

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