Android
 Computer >> コンピューター >  >> プログラミング >> Android

Androidでバブルチャートグラフを使用する方法|MPAndroidChartによる実装手順を解説

本記事では、人気のグラフ描画ライブラリ「MPAndroidChart」を使用して、Androidアプリにバブルチャート(Bubble Chart)を表示する方法を、実際のコード例とともにステップバイステップで解説します。

手順1:新規プロジェクトの作成

Android Studioを起動し、メニューから「File → New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトをセットアップしてください。

手順2:モジュールレベルのbuild.gradleに依存関係を追加

build.gradle(モジュールレベル)を開き、以下のようにライブラリの依存関係を追加します。ポイントはdependenciesブロック内のMPAndroidChartの記述です。

apply plugin: 'com.android.application'
android {
    packagingOptions {
        exclude 'META-INF/proguard/androidx-annotations.pro'
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.andy.myapplication"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

手順3:プロジェクトレベルのbuild.gradleにリポジトリを追加

次に、プロジェクト(トップ)レベルのbuild.gradleを開き、allprojectsブロックにJitPackリポジトリを追加します。これにより、GitHubで公開されているMPAndroidChartライブラリを取得できるようになります。

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}
task clean(type: Delete) {
   delete rootProject.buildDir
}

手順4:レイアウトファイル(activity_main.xml)の編集

res/layout/activity_main.xmlに以下のコードを追加します。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:app = "https://schemas.android.com/apk/res-auto"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <com.github.mikephil.charting.charts.BubbleChart
      android:id = "@+id/BubbleChart"
      android:layout_width = "fill_parent"
      android:layout_height = "fill_parent" />
</android.support.constraint.ConstraintLayout>

このコードでは、バブルチャートを画面いっぱいに表示するためのBubbleChartビューを配置しています。

手順5:MainActivity.javaにチャート処理を実装

src/MainActivity.javaに以下のコードを記述します。

package com.example.andy.myapplication;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.mikephil.charting.charts.BubbleChart;
import com.github.mikephil.charting.charts.CandleStickChart;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.BubbleDataSet;
import com.github.mikephil.charting.data.BubbleEntry;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    BubbleChart bubbleChart;
    BubbleData bubbleData;
    BubbleDataSet bubbleDataSet;
    ArrayList bubbleEntries;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bubbleChart = findViewById(R.id.BubbleChart);
        getEntries();
        bubbleDataSet = new BubbleDataSet(bubbleEntries, "");
        bubbleData = new BubbleData(bubbleDataSet);
        bubbleChart.setData(bubbleData);
        bubbleDataSet.setColors(ColorTemplate.JOYFUL_COLORS);
        bubbleDataSet.setValueTextColor(Color.BLACK);
        bubbleDataSet.setValueTextSize(18f);
    }
    private void getEntries() {
      bubbleEntries = new ArrayList<>();
      bubbleEntries.add(new BubbleEntry(0, 1,0.21f));
      bubbleEntries.add(new BubbleEntry(1, 2,0.12f));
      bubbleEntries.add(new BubbleEntry(2, 3,0.20f));
      bubbleEntries.add(new BubbleEntry(2,4, 0.52f));
      bubbleEntries.add(new BubbleEntry(3, 5,0.29f));
      bubbleEntries.add(new BubbleEntry(4, 6,0.62f));
   }
}

コードのポイント

BubbleEntryのコンストラクタには「X座標・Y座標・バブルのサイズ」の3つの値を渡します。ここではgetEntries()メソッドでサンプルデータを作成し、ColorTemplateのJOYFUL_COLORSを適用することで、カラフルなバブルを描画しています。また、値テキストの色とサイズもsettersでカスタマイズしています。

アプリの実行と結果確認

それではアプリを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続した状態で、Android Studioからプロジェクトのアクティビティファイルを開き、ツールバーのRunアイコンをクリックします。デバイスとして自分のスマートフォンを選択すると、端末の画面に以下のようなバブルチャートが表示されます。

Androidでバブルチャートグラフを使用する方法|MPAndroidChartによる実装手順を解説

上記の実行結果のように、データセットに設定した値に応じて、各バブルの位置や大きさが正しく反映されたバブルチャートが描画されていることが確認できます。

  1. 【Android】LocalBroadcastManagerの使い方を実例付きでわかりやすく解説

    LocalBroadcastManagerとは? LocalBroadcastManagerは、アプリ内部だけで完結するブロードキャスト(Intent)の送受信を行うためのクラスです。システム全体や他アプリには通知されないため、セキュリティ面でも安全で、アプリ内のコンポーネント間でデータを受け渡したい場合に便利です。 本記事では、実際に動くサンプルプロジェクトを作りながら、LocalBroadcastManagerの基本的な実装手順をステップごとに紹介します。 Step 1:新規プロジェクトの作成 まず、Android Studioを起動し、「File → New Project」から新しい

  2. 【Android】ViewFlipperの使い方を徹底解説!ビュー切り替えアニメーションの実装方法

    ViewFlipperとは?ViewFlipperは、複数の子ビューを重ねて保持し、一定間隔での自動切り替えやボタン操作による手動切り替えを、アニメーション効果付きで実現できるAndroidのウィジェットです。画像スライダー、オンボーディング画面、シンプルなカルーセルUIなどを作りたいときに非常に便利です。本記事では、ViewFlipperを使ってImageView・Button・TextViewをスライドアニメーションで切り替えるサンプルアプリを、ステップごとに詳しく解説します。Step 1:新規プロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New