Androidで棒グラフを実装する方法!MPAndroidChartの使い方を解説
この記事では、Androidアプリに棒グラフ(バーチャート)を表示する方法を、定番ライブラリ「MPAndroidChart」を使ってステップごとに解説します。Gradleの設定からレイアウトXML、Javaコードまで、サンプルコード付きで紹介するので、初心者の方でもそのまま実装できます。
手順1:Android Studioで新規プロジェクトを作成する
まず、Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。
手順2:モジュールレベルのbuild.gradleに依存関係を追加する
次に、build.gradle(モジュールレベル)を開き、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'
}
ポイントとなるのは、dependenciesブロック内の implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha' の行です。これにより、棒グラフをはじめとする各種チャート機能が使えるようになります。
手順3:アプリケーションレベルのbuild.gradleにリポジトリを追加する
続いて、build.gradle(プロジェクトレベル)を開き、JitPackリポジトリを追加します。MPAndroidChartはJitPack経由で配布されているため、この設定がないとライブラリを取得できません。
// 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にBarChartビューを配置する
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.BarChart
android:id = "@+id/BarChart"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent" />
</android.support.constraint.ConstraintLayout>
上記のコードでは、棒グラフを表示するためのBarChartビューを画面いっぱいに配置しています。
手順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.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
BarChart barChart;
BarData barData;
BarDataSet barDataSet;
ArrayList barEntries;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
barChart = findViewById(R.id.BarChart);
getEntries();
barDataSet = new BarDataSet(barEntries, "");
barData = new BarData(barDataSet);
barChart.setData(barData);
barDataSet.setColors(ColorTemplate.JOYFUL_COLORS);
barDataSet.setValueTextColor(Color.BLACK);
barDataSet.setValueTextSize(18f);
}
private void getEntries() {
barEntries = new ArrayList<>();
barEntries.add(new BarEntry(2f, 0));
barEntries.add(new BarEntry(4f, 1));
barEntries.add(new BarEntry(6f, 1));
barEntries.add(new BarEntry(8f, 3));
barEntries.add(new BarEntry(7f, 4));
barEntries.add(new BarEntry(3f, 3));
}
}
このコードでは、getEntries()メソッドでデータエントリ(値とインデックス)を作成し、それをBarDataSetに渡しています。さらに、ColorTemplate.JOYFUL_COLORSでカラフルな棒の色を指定し、数値ラベルの文字色とサイズも設定しています。
アプリケーションを実行して確認する
それでは、アプリケーションを実行してみましょう。実際のAndroidスマートフォンをパソコンに接続しているものとします。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run(再生)」アイコンをクリックします。実行デバイスとして自分のモバイル端末を選択すると、端末に以下のような画面が表示されます。

上記の実行結果のように、設定したデータセットの値に沿って、色分けされた棒グラフが正しく描画されていることが確認できます。
-
【Android】ViewFlipperの使い方を徹底解説!ビュー切り替えアニメーションの実装方法
ViewFlipperとは?ViewFlipperは、複数の子ビューを重ねて保持し、一定間隔での自動切り替えやボタン操作による手動切り替えを、アニメーション効果付きで実現できるAndroidのウィジェットです。画像スライダー、オンボーディング画面、シンプルなカルーセルUIなどを作りたいときに非常に便利です。本記事では、ViewFlipperを使ってImageView・Button・TextViewをスライドアニメーションで切り替えるサンプルアプリを、ステップごとに詳しく解説します。Step 1:新規プロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New
-
【Android】スナックバー(Snackbar)の使い方をステップごとに解説
このチュートリアルでは、Androidアプリでスナックバー(Snackbar)を使用する方法を、サンプルコードとともに段階的に解説します。スナックバーは画面下部に短いメッセージを一時的に表示できるUIコンポーネントで、Toastとは異なり「再試行(RETRY)」などのアクションボタンを組み込めるのが大きな特徴です。 手順1:新規プロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。 手順2:レイアウトファイル(activity_main.xml)を編集する