다음 프로젝트에서 차트를 그릴 생각이라면 이 튜토리얼이 적합합니다. 이 자습서에서는 최고의 Android 차트 라이브러리와 사용 방법을 살펴보고자 합니다.
(ㅏ). MPAndroid 차트
강력한 로켓 안드로이드 차트 보기/그래프 보기 라이브러리로 라인-바파이-레이더-버블-및 캔들스틱 차트는 물론 스케일링, 패닝 및 애니메이션을 지원합니다.
지원하는 기능은 다음과 같습니다.
- 다양한 차트 유형: LineChart, BarChart(수직, 수평, 누적, 그룹화), PieChart, ScatterChart, CandleStickChart(재무 데이터용), RadarChart(스파이더 웹 차트), BubbleChart
- 결합된 차트(예: 하나의 선과 막대)
- 두 축 모두에서 크기 조정(터치 제스처, 축 개별 또는 핀치 줌 사용)
- 드래그/패닝(터치 제스처 사용)
- 별도(이중) y축
- 값 강조 표시(맞춤형 팝업 보기 포함)
- SD 카드에 차트 저장(이미지로)
- 사전 정의된 색상 템플릿
- 범례(자동 생성, 사용자 정의 가능)
- 사용자 정의 가능한 축(x축 및 y축 모두)
- 애니메이션(x축 및 y축 모두에서 애니메이션 빌드)
- 한계선(추가 정보, 최대값, … 제공)
- 터치, 제스처 및 선택 콜백을 위한 리스너
- 완전히 사용자 정의 가능(페인트, 서체, 범례, 색상, 배경, 점선 등)
- MPAndroidChart-Realm 라이브러리를 통한 Realm.io 모바일 데이터베이스 지원
- Line- 및 BarChart에서 최대 10.000 데이터 포인트에 대한 부드러운 렌더링(Android 6.0을 실행하는 2014 OnePlus One에서 테스트됨)
- 경량(메소드 수 ~1.4K)
- .jar 파일로 사용 가능(크기 500kb)
- gradle 종속성 및 maven을 통해 사용 가능
- Google-PlayStore 데모 애플리케이션
- 널리 사용되는 GitHub 및 stackoverflow – mpandroidchart
- iOS에서도 사용 가능: Charts (API는 동일한 방식으로 작동합니다)
- Xamarin에서도 사용 가능: MPAndroidChart.Xamarin
- [동적 및 실시간 데이터]에 대한 제한된 지원(https://weeklycoding.com/mpandroidchart-documentation/dynamic-realtime-data/)
1단계: 설치
루트 수준 build.gradle에서 jitpack을 maven Url로 등록하여 시작합니다.
repositories {
maven { url 'https://jitpack.io' }
}
이제 앱 수준 build.gradle로 이동하여 종속성을 선언합니다.
dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}
2단계: 예
다음은 이 라이브러리를 사용한 BarChart 생성 활동의 예입니다.
public class BarChartActivity extends DemoBase implements OnSeekBarChangeListener,
OnChartValueSelectedListener {
private BarChart chart;
private SeekBar seekBarX, seekBarY;
private TextView tvX, tvY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_barchart);
setTitle("BarChartActivity");
tvX = findViewById(R.id.tvXMax);
tvY = findViewById(R.id.tvYMax);
seekBarX = findViewById(R.id.seekBar1);
seekBarY = findViewById(R.id.seekBar2);
seekBarY.setOnSeekBarChangeListener(this);
seekBarX.setOnSeekBarChangeListener(this);
chart = findViewById(R.id.chart1);
chart.setOnChartValueSelectedListener(this);
chart.setDrawBarShadow(false);
chart.setDrawValueAboveBar(true);
chart.getDescription().setEnabled(false);
// if more than 60 entries are displayed in the chart, no values will be
// drawn
chart.setMaxVisibleValueCount(60);
// scaling can now only be done on x- and y-axis separately
chart.setPinchZoom(false);
chart.setDrawGridBackground(false);
// chart.setDrawYLabels(false);
IAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(chart);
XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxisPosition.BOTTOM);
xAxis.setTypeface(tfLight);
xAxis.setDrawGridLines(false);
xAxis.setGranularity(1f); // only intervals of 1 day
xAxis.setLabelCount(7);
xAxis.setValueFormatter(xAxisFormatter);
IAxisValueFormatter custom = new MyAxisValueFormatter();
YAxis leftAxis = chart.getAxisLeft();
leftAxis.setTypeface(tfLight);
leftAxis.setLabelCount(8, false);
leftAxis.setValueFormatter(custom);
leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
leftAxis.setSpaceTop(15f);
leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
YAxis rightAxis = chart.getAxisRight();
rightAxis.setDrawGridLines(false);
rightAxis.setTypeface(tfLight);
rightAxis.setLabelCount(8, false);
rightAxis.setValueFormatter(custom);
rightAxis.setSpaceTop(15f);
rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
Legend l = chart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
l.setForm(LegendForm.SQUARE);
l.setFormSize(9f);
l.setTextSize(11f);
l.setXEntrySpace(4f);
XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);
mv.setChartView(chart); // For bounds control
chart.setMarker(mv); // Set the marker to the chart
// setting data
seekBarY.setProgress(50);
seekBarX.setProgress(12);
// chart.setDrawLegend(false);
}
private void setData(int count, float range) {
float start = 1f;
ArrayList<BarEntry> values = new ArrayList<>();
for (int i = (int) start; i < start + count; i++) {
float val = (float) (Math.random() * (range + 1));
if (Math.random() * 100 < 25) {
values.add(new BarEntry(i, val, getResources().getDrawable(R.drawable.star)));
} else {
values.add(new BarEntry(i, val));
}
}
BarDataSet set1;
if (chart.getData() != null &&
chart.getData().getDataSetCount() > 0) {
set1 = (BarDataSet) chart.getData().getDataSetByIndex(0);
set1.setValues(values);
chart.getData().notifyDataChanged();
chart.notifyDataSetChanged();
} else {
set1 = new BarDataSet(values, "The year 2017");
set1.setDrawIcons(false);
int startColor1 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
int startColor2 = ContextCompat.getColor(this, android.R.color.holo_blue_light);
int startColor3 = ContextCompat.getColor(this, android.R.color.holo_orange_light);
int startColor4 = ContextCompat.getColor(this, android.R.color.holo_green_light);
int startColor5 = ContextCompat.getColor(this, android.R.color.holo_red_light);
int endColor1 = ContextCompat.getColor(this, android.R.color.holo_blue_dark);
int endColor2 = ContextCompat.getColor(this, android.R.color.holo_purple);
int endColor3 = ContextCompat.getColor(this, android.R.color.holo_green_dark);
int endColor4 = ContextCompat.getColor(this, android.R.color.holo_red_dark);
int endColor5 = ContextCompat.getColor(this, android.R.color.holo_orange_dark);
List<Fill> gradientFills = new ArrayList<>();
gradientFills.add(new Fill(startColor1, endColor1));
gradientFills.add(new Fill(startColor2, endColor2));
gradientFills.add(new Fill(startColor3, endColor3));
gradientFills.add(new Fill(startColor4, endColor4));
gradientFills.add(new Fill(startColor5, endColor5));
set1.setFills(gradientFills);
ArrayList<IBarDataSet> dataSets = new ArrayList<>();
dataSets.add(set1);
BarData data = new BarData(dataSets);
data.setValueTextSize(10f);
data.setValueTypeface(tfLight);
data.setBarWidth(0.9f);
chart.setData(data);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.viewGithub: {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/com/xxmassdeveloper/mpchartexample/BarChartActivity.java"));
startActivity(i);
break;
}
case R.id.actionToggleValues: {
for (IDataSet set : chart.getData().getDataSets())
set.setDrawValues(!set.isDrawValuesEnabled());
chart.invalidate();
break;
}
case R.id.actionToggleIcons: {
for (IDataSet set : chart.getData().getDataSets())
set.setDrawIcons(!set.isDrawIconsEnabled());
chart.invalidate();
break;
}
case R.id.actionToggleHighlight: {
if (chart.getData() != null) {
chart.getData().setHighlightEnabled(!chart.getData().isHighlightEnabled());
chart.invalidate();
}
break;
}
case R.id.actionTogglePinch: {
if (chart.isPinchZoomEnabled())
chart.setPinchZoom(false);
else
chart.setPinchZoom(true);
chart.invalidate();
break;
}
case R.id.actionToggleAutoScaleMinMax: {
chart.setAutoScaleMinMaxEnabled(!chart.isAutoScaleMinMaxEnabled());
chart.notifyDataSetChanged();
break;
}
case R.id.actionToggleBarBorders: {
for (IBarDataSet set : chart.getData().getDataSets())
((BarDataSet) set).setBarBorderWidth(set.getBarBorderWidth() == 1.f ? 0.f : 1.f);
chart.invalidate();
break;
}
case R.id.animateX: {
chart.animateX(2000);
break;
}
case R.id.animateY: {
chart.animateY(2000);
break;
}
case R.id.animateXY: {
chart.animateXY(2000, 2000);
break;
}
case R.id.actionSave: {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
saveToGallery();
} else {
requestStoragePermission(chart);
}
break;
}
}
return true;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvX.setText(String.valueOf(seekBarX.getProgress()));
tvY.setText(String.valueOf(seekBarY.getProgress()));
setData(seekBarX.getProgress(), seekBarY.getProgress());
chart.invalidate();
}
@Override
protected void saveToGallery() {
saveToGallery(chart, "BarChartActivity");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
private final RectF onValueSelectedRectF = new RectF();
@Override
public void onValueSelected(Entry e, Highlight h) {
if (e == null)
return;
RectF bounds = onValueSelectedRectF;
chart.getBarBounds((BarEntry) e, bounds);
MPPointF position = chart.getPosition(e, AxisDependency.LEFT);
Log.i("bounds", bounds.toString());
Log.i("position", position.toString());
Log.i("x-index",
"low: " + chart.getLowestVisibleX() + ", high: "
+ chart.getHighestVisibleX());
MPPointF.recycleInstance(position);
}
@Override
public void onNothingSelected() { }
}
아래에 제공된 다운로드 링크에 수십 개의 그러한 예가 있습니다.
참조
아래 링크에서 다운로드하거나 더 읽어보세요.
번호 | 링크 |
---|---|
1. | 다운로드 예제 |
2. | 읽기 더보기 |
(ㄴ). 안드로이드차트
애니메이션이 포함된 사용하기 쉬운 Android 차트 라이브러리.
1단계: 설치
app/build.gradle
에 다음 구현 문을 추가하고 동기화합니다.
implementation 'im.dacer:AndroidCharts:1.0.4'
2단계: 레이아웃에 추가
다음과 같이 레이아웃에 추가합니다.
선 그래프 예
<HorizontalScrollView>
<view
android:layout_width="wrap_content"
android:layout_height="300dp"
class="im.dacer.androidcharts.LineView"
android:id="@+id/line_view" />
</HorizontalScrollView>
막대 차트 예시
<HorizontalScrollView>
<view
android:layout_width="wrap_content"
android:layout_height="300dp"
class="im.dacer.androidcharts.BarView"
android:id="@+id/bar_view" />
</HorizontalScrollView>
파이 차트
이 보기에서 우리는 파이 차트를 그릴 것입니다:
<view
android:layout_width="300dp"
android:layout_height="wrap_content"
class="im.dacer.androidcharts.PieView"
android:id="@+id/pie_view" />
3단계: 코드 작성
차트 보기를 참조하고 여기에 데이터를 첨부합니다.
선 그래프 예
LineView lineView = (LineView)findViewById(R.id.line_view);
lineView.setDrawDotLine(false); //optional
lineView.setShowPopup(LineView.SHOW_POPUPS_MAXMIN_ONLY); //optional
lineView.setBottomTextList(strList);
lineView.setColorArray(new int[]{Color.BLACK,Color.GREEN,Color.GRAY,Color.CYAN});
lineView.setDataList(dataLists); //or lineView.setFloatDataList(floatDataLists)
막대 차트 예시
BarChart를 그리는 방법은 다음과 같습니다.
BarView barView = (BarView)findViewById(R.id.bar_view);\
barView.setBottomTextList(strList);
barView.setDataList(dataList,100);
파이 차트
PirChart를 그리는 방법은 다음과 같습니다.
PieView pieView = (PieView)findViewById(R.id.pie_view);
ArrayList<PieHelper> pieHelperArrayList = new ArrayList<PieHelper>();
pieView.setDate(pieHelperArrayList);
pieView.selectedPie(2); //optional
pieView.setOnPieClickListener(listener) //optional
pieView.showPercentLabel(false); //optional
전체 예
바프래그먼트
다음은 BarChart를 렌더링하는 Fragment의 예입니다.
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import im.dacer.androidcharts.BarView;
import java.util.ArrayList;
/**
* Created by Dacer on 11/15/13.
*/
public class BarFragment extends Fragment {
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bar, container, false);
final BarView barView = (BarView) rootView.findViewById(R.id.bar_view);
Button button = (Button) rootView.findViewById(R.id.bar_button);
button.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
randomSet(barView);
}
});
randomSet(barView);
return rootView;
}
private void randomSet(BarView barView) {
int random = (int) (Math.random() * 20) + 6;
ArrayList<String> test = new ArrayList<String>();
for (int i = 0; i < random; i++) {
test.add("test");
test.add("pqg");
// test.add(String.valueOf(i+1));
}
barView.setBottomTextList(test);
ArrayList<Integer> barDataList = new ArrayList<Integer>();
for (int i = 0; i < random * 2; i++) {
barDataList.add((int) (Math.random() * 100));
}
barView.setDataList(barDataList, 100);
}
}
여기에서 더 많은 예시를 찾아보세요.
참조
아래는 참조 링크입니다.
번호 | 링크 |
---|---|
1. | 다운로드 예제 |
2. | 읽기 더보기 |
(씨). 헬로차트
API 8 이상과 호환되는 Android용 차트/그래프 라이브러리, 스케일링, 스크롤링 및 애니메이션을 지원하는 여러 차트 유형
하드웨어 가속을 사용할 수 있을 때 가장 잘 작동하므로 API 14+(Android 4.0)를 권장합니다. 아파치 라이선스 2.0.
핵심 기능은 다음과 같습니다.
- 꺾은선형 차트(입방선, 채워진 선, 산점)
- 세로 막대형 차트(그룹화, 누적, 음수 값)
- 파이 차트
- 버블 차트
- 콤보 차트(열/선)
- 미리보기 차트(컬럼 차트 및 라인 차트용)
- 줌(핀치하여 줌, 더블 탭 줌), 스크롤 및 플링
- 사용자 지정 및 자동 생성 축(위, 아래, 왼쪽, 오른쪽, 내부)
- 애니메이션
1단계: 설치
이 라이브러리를 설치할 수 있는 두 개의 저장소:
메이븐센트럴
implementation 'com.github.lecho:hellocharts-library:1.5.8@aar'
지트팩
Jitpack에서 jitpack을 maven 저장소로 등록하여 시작합니다.
repositories {
maven {
url "https://jitpack.io"
}
}
그런 다음 종속성을 추가합니다.
dependencies {
implementaion 'com.github.lecho:hellocharts-android:v1.5.8'
}
식
- 최신 릴리스 jar 파일을 다운로드합니다.
hellocharts-library-<version>.jar
을 애플리케이션 프로젝트의libs
폴더에 복사합니다.
2단계: 레이아웃에 추가
예를 들어 LineChart의 경우 적절한 HelloChart를 레이아웃에 추가합니다.
<lecho.lib.hellocharts.view.LineChartView
android:id="@+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
3단계: 코드 작성
차트를 참조하거나 프로그래밍 방식으로 생성할 수 있습니다.
LineChartView chart = new LineChartView(context);
layout.addView(chart);
그런 다음 차트 동작을 제어합니다.
Chart.setInteractive(boolean isInteractive);
Chart.setZoomType(ZoomType zoomType);
Chart.setContainerScrollEnabled(boolean isEnabled, ContainerScrollType type);
그런 다음 데이터 모델 메서드를 사용하여 차트 모양을 제어합니다.
ChartData.setAxisXBottom(Axis axisX);
ColumnChartData.setStacked(boolean isStacked);
Line.setStrokeWidth(int strokeWidthDp);
사용된 차트 유형에 따라 차트 데이터 및 모델 설정:
List<PointValue> values = new ArrayList<PointValue>();
values.add(new PointValue(0, 2));
values.add(new PointValue(1, 4));
values.add(new PointValue(2, 3));
values.add(new PointValue(3, 4));
//In most cased you can call data model methods in builder-pattern-like manner.
Line line = new Line(values).setColor(Color.BLUE).setCubic(true);
List<Line> lines = new ArrayList<Line>();
lines.add(line);
LineChartData data = new LineChartData();
data.setLines(lines);
LineChartView chart = new LineChartView(context);
chart.setLineChartData(data);
예시
다음은 PieChart의 예입니다.
PieChartActivity.java
public class PieChartActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pie_chart);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
/**
* A fragment containing a pie chart.
*/
public static class PlaceholderFragment extends Fragment {
private PieChartView chart;
private PieChartData data;
private boolean hasLabels = false;
private boolean hasLabelsOutside = false;
private boolean hasCenterCircle = false;
private boolean hasCenterText1 = false;
private boolean hasCenterText2 = false;
private boolean isExploded = false;
private boolean hasLabelForSelected = false;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.fragment_pie_chart, container, false);
chart = (PieChartView) rootView.findViewById(R.id.chart);
chart.setOnValueTouchListener(new ValueTouchListener());
generateData();
return rootView;
}
// MENU
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.pie_chart, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_reset) {
reset();
generateData();
return true;
}
if (id == R.id.action_explode) {
explodeChart();
return true;
}
if (id == R.id.action_center_circle) {
hasCenterCircle = !hasCenterCircle;
if (!hasCenterCircle) {
hasCenterText1 = false;
hasCenterText2 = false;
}
generateData();
return true;
}
if (id == R.id.action_center_text1) {
hasCenterText1 = !hasCenterText1;
if (hasCenterText1) {
hasCenterCircle = true;
}
hasCenterText2 = false;
generateData();
return true;
}
if (id == R.id.action_center_text2) {
hasCenterText2 = !hasCenterText2;
if (hasCenterText2) {
hasCenterText1 = true;// text 2 need text 1 to by also drawn.
hasCenterCircle = true;
}
generateData();
return true;
}
if (id == R.id.action_toggle_labels) {
toggleLabels();
return true;
}
if (id == R.id.action_toggle_labels_outside) {
toggleLabelsOutside();
return true;
}
if (id == R.id.action_animate) {
prepareDataAnimation();
chart.startDataAnimation();
return true;
}
if (id == R.id.action_toggle_selection_mode) {
toggleLabelForSelected();
Toast.makeText(getActivity(),
"Selection mode set to " + chart.isValueSelectionEnabled() + " select any point.",
Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
private void reset() {
chart.setCircleFillRatio(1.0f);
hasLabels = false;
hasLabelsOutside = false;
hasCenterCircle = false;
hasCenterText1 = false;
hasCenterText2 = false;
isExploded = false;
hasLabelForSelected = false;
}
private void generateData() {
int numValues = 6;
List<SliceValue> values = new ArrayList<SliceValue>();
for (int i = 0; i < numValues; ++i) {
SliceValue sliceValue = new SliceValue((float) Math.random() * 30 + 15, ChartUtils.pickColor());
values.add(sliceValue);
}
data = new PieChartData(values);
data.setHasLabels(hasLabels);
data.setHasLabelsOnlyForSelected(hasLabelForSelected);
data.setHasLabelsOutside(hasLabelsOutside);
data.setHasCenterCircle(hasCenterCircle);
if (isExploded) {
data.setSlicesSpacing(24);
}
if (hasCenterText1) {
data.setCenterText1("Hello!");
// Get roboto-italic font.
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Italic.ttf");
data.setCenterText1Typeface(tf);
// Get font size from dimens.xml and convert it to sp(library uses sp values).
data.setCenterText1FontSize(ChartUtils.px2sp(getResources().getDisplayMetrics().scaledDensity,
(int) getResources().getDimension(R.dimen.pie_chart_text1_size)));
}
if (hasCenterText2) {
data.setCenterText2("Charts (Roboto Italic)");
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Italic.ttf");
data.setCenterText2Typeface(tf);
data.setCenterText2FontSize(ChartUtils.px2sp(getResources().getDisplayMetrics().scaledDensity,
(int) getResources().getDimension(R.dimen.pie_chart_text2_size)));
}
chart.setPieChartData(data);
}
private void explodeChart() {
isExploded = !isExploded;
generateData();
}
private void toggleLabelsOutside() {
// has labels have to be true:P
hasLabelsOutside = !hasLabelsOutside;
if (hasLabelsOutside) {
hasLabels = true;
hasLabelForSelected = false;
chart.setValueSelectionEnabled(hasLabelForSelected);
}
if (hasLabelsOutside) {
chart.setCircleFillRatio(0.7f);
} else {
chart.setCircleFillRatio(1.0f);
}
generateData();
}
private void toggleLabels() {
hasLabels = !hasLabels;
if (hasLabels) {
hasLabelForSelected = false;
chart.setValueSelectionEnabled(hasLabelForSelected);
if (hasLabelsOutside) {
chart.setCircleFillRatio(0.7f);
} else {
chart.setCircleFillRatio(1.0f);
}
}
generateData();
}
private void toggleLabelForSelected() {
hasLabelForSelected = !hasLabelForSelected;
chart.setValueSelectionEnabled(hasLabelForSelected);
if (hasLabelForSelected) {
hasLabels = false;
hasLabelsOutside = false;
if (hasLabelsOutside) {
chart.setCircleFillRatio(0.7f);
} else {
chart.setCircleFillRatio(1.0f);
}
}
generateData();
}
/**
* To animate values you have to change targets values and then call {@link Chart#startDataAnimation()}
* method(don't confuse with View.animate()).
*/
private void prepareDataAnimation() {
for (SliceValue value : data.getValues()) {
value.setTarget((float) Math.random() * 30 + 15);
}
}
private class ValueTouchListener implements PieChartOnValueSelectListener {
@Override
public void onValueSelected(int arcIndex, SliceValue value) {
Toast.makeText(getActivity(), "Selected: " + value, Toast.LENGTH_SHORT).show();
}
@Override
public void onValueDeselected() {
// TODO Auto-generated method stub
}
}
}
}
전체 예제 코드는 여기에서 찾을 수 있습니다.
참조
아래에서 다운로드 링크를 찾으십시오.