Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีใช้กราฟวงกลม (Pie Chart) ใน Android

การสร้างกราฟวงกลมด้วยไลบรารี MPAndroidChart

บทความนี้จะแนะนำวิธีการนำเสนอข้อมูลด้วยกราฟวงกลม (Pie Chart) ในแอปพลิเคชัน Android โดยใช้ไลบรารี MPAndroidChart ซึ่งเป็นไลบรารียอดนิยมสำหรับการสร้างกราฟประเภทต่างๆ

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่ใน Android Studio

เปิด Android Studio → File → New Project → เลือก Empty Activity → กรอกข้อมูลที่จำเป็น → Finish

ขั้นตอนที่ 2: เพิ่ม Dependency ใน build.gradle (Module Level)

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.piechartdemo"
        minSdkVersion 21
        targetSdkVersion 34
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

หมายเหตุ: ตัวอย่างโค้ดนี้ได้ปรับปรุงให้ใช้ AndroidX และเวอร์ชันล่าสุด แทนที่ Support Library ที่ล้าสมัยแล้ว

ขั้นตอนที่ 3: เพิ่ม Repository ใน build.gradle (Project Level)

// Top-level build file
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:8.1.0'
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' }
    }
}

tasks.register("clean", Delete) {
    delete rootProject.buildDir
}

ขั้นตอนที่ 4: ออกแบบ Layout ใน activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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.PieChart
        android:id="@+id/pieChart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="16dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

ขั้นตอนที่ 5: เขียนโค้ดใน MainActivity.java

package com.example.piechartdemo;

import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private PieChart pieChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pieChart = findViewById(R.id.pieChart);
        setupPieChart();
    }

    private void setupPieChart() {
        ArrayList<PieEntry> entries = new ArrayList<>();
        entries.add(new PieEntry(30f, "มกราคม"));
        entries.add(new PieEntry(25f, "กุมภาพันธ์"));
        entries.add(new PieEntry(20f, "มีนาคม"));
        entries.add(new PieEntry(15f, "เมษายน"));
        entries.add(new PieEntry(10f, "พฤษภาคม"));

        PieDataSet dataSet = new PieDataSet(entries, "ยอดขายรายเดือน");
        dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
        dataSet.setValueTextColor(Color.WHITE);
        dataSet.setValueTextSize(12f);
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        PieData pieData = new PieData(dataSet);
        pieChart.setData(pieData);
        pieChart.getDescription().setEnabled(false);
        pieChart.setCenterText("สรุปยอดขาย");
        pieChart.setCenterTextSize(16f);
        pieChart.setCenterTextColor(Color.BLACK);
        pieChart.animateY(1000);
        pieChart.invalidate(); // refresh
    }
}

การทดสอบแอปพลิเคชัน

เชื่อมต่ออุปกรณ์ Android จริงหรือใช้ Emulator → กดปุ่ม Run ใน Android Studio → เลือกอุปกรณ์เป้าหมาย → แอปจะแสดงกราฟวงกลมพร้อมแอนิเมชัน

คุณสมบัติเพิ่มเติมที่น่าสนใจ

  • แอนิเมชัน: ใช้ animateY() หรือ animateX() เพื่อเพิ่มความน่าสนใจ
  • การตั้งค่าสี: สามารถกำหนดสีเองได้ด้วย dataSet.setColors()
  • Legend: ปิด/เปิดได้ด้วย pieChart.getLegend().setEnabled(false)
  • การคลิกเลือก: ใช้ OnChartValueSelectedListener เพื่อจับเหตุการณ์เมื่อผู้ใช้กดที่แต่ละส่วน

ข้อควรระวัง

หากพบข้อผิดพลาด "Failed to resolve: com.github.PhilJay:MPAndroidChart" ให้ตรวจสอบว่าได้เพิ่ม maven { url 'https://jitpack.io' } ใน project-level build.gradle แล้ว และ Sync Project ใหม่อีกครั้ง