Согласно моему требованию, я хочу использовать круговые диаграммы в своем приложении для Android. Я хочу показать как минимум 2 круговых диаграммы в своей основной деятельности, и я использую MPAndroid для отображения графика. Как использовать метод onValueSelected для всех трех диаграмм, отображаемых в моем макете основной активности.
пакет com.harshulexample.itochuparekh;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class Piechart extends AppCompatActivity implements OnChartValueSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_piechart);
showCustomTitle();
showpiechart();
}
private void showCustomTitle(){
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1B4386")));
LayoutInflater li=getLayoutInflater();
View v = li.inflate(R.layout.tracking_actionbar, null);
actionBar.setCustomView(v);
}
private void showpiechart(){
PieChart pieChart = (PieChart) findViewById(R.id.piechart);
PieChart piechartt=findViewById(R.id.piechartt);
pieChart.setUsePercentValues(true);
piechartt.setUsePercentValues(true);
// IMPORTANT: In a PieChart, no values (Entry) should have the same
// xIndex (even if from different DataSets), since no values can be
// drawn above each other.
ArrayList<Entry> yvalues = new ArrayList<Entry>();
yvalues.add(new Entry(9f, 0));
yvalues.add(new Entry(13f, 1));
yvalues.add(new Entry(13f, 2));
yvalues.add(new Entry(25f, 3));
yvalues.add(new Entry(23f, 4));
yvalues.add(new Entry(17f, 5));
PieDataSet dataSet = new PieDataSet(yvalues, "Election Results");
ArrayList<String> xVals = new ArrayList<String>();
xVals.add("Unicharm");
xVals.add("Honda");
xVals.add("CPW");
xVals.add("Cremica");
xVals.add("SOfy");
xVals.add("Hero");
PieData data = new PieData(xVals, dataSet);
data.setValueFormatter(new PercentFormatter());
pieChart.setData(data);
piechartt.setData(data);
pieChart.setDescription("MAJOR CLIENTS");
piechartt.setDescription("MAJOR CLIENTS");
pieChart.setDrawHoleEnabled(true);
piechartt.setDrawHoleEnabled(true);
pieChart.setTransparentCircleRadius(25f);
pieChart.setHoleRadius(25f);
piechartt.setTransparentCircleRadius(25f);
piechartt.setHoleRadius(25f);
dataSet.setColors(new int[] { R.color.babypink, R.color.violet, R.color.yellow, R.color.Green,R.color.Blue,R.color.colorAccent,R.color.colorPrimary },this);
data.setValueTextSize(15f);
data.setValueTextColor(Color.DKGRAY);
pieChart.setOnChartValueSelectedListener(this);
piechartt.setOnChartValueSelectedListener(this);
pieChart.animateXY(1400, 1400);
piechartt.animateXY(1400, 1400);
}
@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
// if (e == null)
// return;
Log.d("Mobile",
"Value: " + e.getVal() + ", xIndex: " + e.getXIndex()
+ ", DataSet index: " + dataSetIndex+"name:"+e.toString()+"may be this:"+e.describeContents()+"or may be this:"+e.getData()+"Entry point: "+e+" Highlight: "+h.toString());
float value=e.getVal();
Log.d("Mobile","This is real value:"+value);
Intent intent=new Intent(this,secondpiechart.class);
intent.putExtra("Client",value);
startActivity(intent);
}
@Override
public void onNothingSelected() {
Log.i("PieChart", "nothing selected");
}
}
и ниже - мой основной макет деятельности.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Piechart"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:gravity="center"
android:textStyle="bold"
android:text="PENDING TRANSACTIONS MONTH-SEP"/>
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/piechart"
android:layout_width="match_parent"
android:layout_height="500dp"/>
<com.github.mikephil.charting.charts.PieChart
android:id="@+id/piechartt"
android:layout_width="match_parent"
android:layout_height="500dp"/>
</LinearLayout>
</ScrollView>
Но я говорю о щелчке по одному пирогу на круговой диаграмме (в моей одной круговой диаграмме 6 пирогов). и я не говорю о нажатии на весь пирог. У меня есть две круговые диаграммы в файле activity_piechat.xml по 6 штук в каждой. При добавлении данных на круговую диаграмму вместе с индексом для каждого кругового (в моем случае у меня есть 6 пирогов для моего индекса, начинающегося с 0 до 5), если я установлю индекс от 0 до 5 для моего первого кругового графика и 6-11 для второй круговой чат, тогда метод onValueSelected не работает вообще. но если я установлю одинаковое значение индекса от 0 до 5 для обеих моих диаграмм, то метод onValueSelected работает. Предположим, я щелкаю нулевую круговую диаграмму моего первого кругового чата, после чего вызывается метод onValueSelected. и если я нажимаю на индекс 0 моей второй круговой диаграммы, то снова вызывается тот же метод. но я хочу различную функциональность для обоих моих круговых диаграмм.
Пожалуйста помоги!
Спасибо