[Android] MPAndroidChart를 사용한 색깔의 PieChart 구현 메모

MPAndroidChart 라이브러리를 사용하여 색상이 지정된 PieChart를 만들 때 구현 메모입니다.

참고 URL:
MPAndroid Chart : htps : // 기주 b. 코 m / P Hi Y y / M Pand Roi d Chart
Wiki Getting Started : htps : // 기주 b. 코 m / P 히 야 y / M 팬 d 로이 d 짱 rt / uki / 갓찐 g S r d
위키 설정 데이터 : htps : // 기주 b. 코 m / P Hi Y y / M Pand Roi d Chart / Uuki / Setchin g-

만드는 것



월별 강수량 비율을 보여주는 PieChart입니다.
달을 클릭하면 조금 확대됩니다.


build.gradle



build.gradle
allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

dependencies {
    implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
}

활동



MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

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;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    float rainfall[] = {98.8f, 123.8f, 34.6f, 43.9f, 69.4f, 12.5f, 52.8f, 158.6f,
            203.6f, 30.7f, 160.7f, 159.7f };
    String monthNames[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
            "Sep", "Oct", "Nov", "Dec"};


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

        setupPieChart();
    }


    private void setupPieChart() {
        //PieEntriesのリストを作成する:
        List<PieEntry> pieEntries = new ArrayList<>();
        for (int i = 0; i < rainfall.length; i++) {
            pieEntries.add(new PieEntry(rainfall[i], monthNames[i]));
        }

        PieDataSet dataSet = new PieDataSet(pieEntries, "Rainfall for Vancouver");
        dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
        PieData data = new PieData(dataSet);

        //PieChartを取得する:
        PieChart piechart = (PieChart) findViewById(R.id.chart);
        piechart.setData(data);
        piechart.invalidate();
    }
}

※덤 메모:
Fragment에 쓸 때 "PieChart piechart = (PieChart) findViewById(R.id.chart);"
"PieChart piechart = (PieChart) getView().findViewById(R.id.chart);"

Layout



activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://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/chart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

끝!

좋은 웹페이지 즐겨찾기