Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to highlight a particular slice of mpandroid pie chart without touching it?

I have implemented the Mpandroid pie chart in my android app ,I have made a BMI calculator ,I wanted to highlight a particular slice of the pie chart according to the BMI result which i get .Is there any solution on how to highlight a particular slice without touching it .For eg. if the BMI is between 10-20 then that particular slice should be highlighted which has the range of 10-20. I dont want my touch to highlight the slice ,I want it to happen automatically according to the BMI result which i obtain.

Here is my code-->

Activity_main.java

    public class MainActivity extends AppCompatActivity
      {

    private RadioGroup radioSexGroup;
    private RadioButton radioSexButton;
    private int selectedId;
    private EditText age;
    private EditText height;
    private EditText weight;
//    private TextView result;
    private TextView t1;
    private Spinner height_spinner;
    private Spinner weight_spinner;
    private Button calculate;
    private PieChart mChart;

    String spinner_height; //Height Spinner
    String spinner_weight; //Weight Spinner
    String selected_item1;
    String selected_item2;

    float bmi=0f;

    protected String[] BMIcategory = new String[]
            {
            "Very Severly Underweight", "Severly Underweight", "Underweight", "Normal",
                    "Overweight", "Obese Class I", "Obese Class II", "Obese Class III",
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle("BMI Calculator");


        radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
        selectedId = radioSexGroup.getCheckedRadioButtonId();
        radioSexButton = (RadioButton) findViewById(selectedId);
        mChart=(PieChart)findViewById(R.id.chart);
        age=(EditText) findViewById(R.id.age);


        height=(EditText) findViewById(R.id.height);
        weight=(EditText) findViewById(R.id.weight);
//        result=(TextView) findViewById(result);
        t1=(TextView) findViewById(R.id.text1);
        t1.setText("<16.00");
        height_spinner=(Spinner) findViewById(R.id.height_spinner);
        weight_spinner=(Spinner) findViewById(R.id.weight_spinner);
        calculate=(Button) findViewById(R.id.calculate_button);

        setchart();
        calculate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                calculate();
            }
        });

        set_spinner();

    }

    public void setchart()
    {
        mChart.setBackgroundColor(Color.rgb(255,255,255));
        mChart.setUsePercentValues(false);
        mChart.getDescription().setEnabled(false);

        mChart.setDrawCenterText(true);
        mChart.setCenterTextTypeface(Typeface.DEFAULT_BOLD);

        mChart.setCenterTextColor(Color.BLACK);
        mChart.setCenterTextSize(18f);
        mChart.setCenterText("BMI:");

        mChart.setDrawHoleEnabled(true);
        mChart.setHoleColor(Color.rgb(255,255,255));

        mChart.setTransparentCircleColor(Color.rgb(255,255,255));
        mChart.setTransparentCircleAlpha(110);

        mChart.setHoleRadius(65f);
        mChart.setTransparentCircleRadius(68f);
        mChart.setDrawSliceText(false);
        mChart.setDrawEntryLabels(false);

        mChart.setRotationEnabled(false);
        mChart.setHighlightPerTapEnabled(false);

        mChart.setMaxAngle(270f); // HALF CHART
        mChart.setRotationAngle(135f);

        setData(8, 80);

    }

    private void setData(int count, float range) {

        ArrayList<PieEntry> values = new ArrayList<>();

        values.add(new PieEntry(10f,BMIcategory[0]));
        values.add(new PieEntry(15f,BMIcategory[1]));
        values.add(new PieEntry(8f,BMIcategory[2]));
        values.add(new PieEntry(12f,BMIcategory[3]));
        values.add(new PieEntry(5f,BMIcategory[4]));
        values.add(new PieEntry(5f,BMIcategory[5]));
        values.add(new PieEntry(15f,BMIcategory[6]));
        values.add(new PieEntry(10f,BMIcategory[7]));


        PieDataSet dataSet = new PieDataSet(values, "BMI Category");
        dataSet.setSliceSpace(0f);
        dataSet.setSelectionShift(5f);
//        dataSet.setColors(Colors);

        // add many colors
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(Color.rgb(31,127,218));
        colors.add(Color.rgb(37,169,254));
        colors.add(Color.rgb(63,200,247));
        colors.add(Color.rgb(65,189,103));
        colors.add(Color.rgb(243,207,0));
        colors.add(Color.rgb(248,154,20));
        colors.add(Color.rgb(238,87,59));
        colors.add(Color.rgb(171,18,14));

        dataSet.setColors(colors);


        PieData data = new PieData(dataSet);
        data.setDrawValues(false);


        mChart.setData(data);
        mChart.invalidate();
    }
    public void set_spinner(){

        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.height_spinner_array, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        height_spinner.setAdapter(adapter1);

        height_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                int a = parent.getSelectedItemPosition();
                spinner_height = height_spinner.getSelectedItem().toString();

                if (a == 0) {
                    selected_item1="Inches";
                }
                if(a==1)
                {
                    selected_item1="Centimeters";
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });


        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.weight_spinner_array, android.R.layout.simple_spinner_item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        weight_spinner.setAdapter(adapter2);
        weight_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                int b = parent.getSelectedItemPosition();
               spinner_weight = weight_spinner.getSelectedItem().toString();
                if(b==0)
                {
                    selected_item2="Kgs";
                }
                if(b==1)
                {
                    selected_item2="Lbs";
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {} } );


    }

    public void calculate() {

//        mChart=(PieChart)findViewById(R.id.chart);
        mChart.setDrawCenterText(true);
        mChart.setCenterTextTypeface(Typeface.DEFAULT_BOLD);
        mChart.setCenterTextColor(Color.BLACK);
        mChart.setCenterTextSize(18f);


        float getHeight, getWeight;

        DecimalFormat df = new DecimalFormat("#0.00");

        if (height.getText().toString().equals("")) {
            getHeight = 0f;
        } else {
            getHeight = Float.parseFloat(height.getText().toString());
        }
        if (weight.getText().toString().equals("")) {
            getWeight = 0f;
        } else {
            getWeight = Float.parseFloat(weight.getText().toString());
        }
        if(height.getText().toString().equals("") || weight.getText().toString().equals("") || age.getText().toString().equals(""))
        {
            bmi=0f;
            mChart.invalidate();
            mChart.setCenterText("BMI:");
            mChart.invalidate();

            Toast.makeText(this,"Please Enter All the Values",Toast.LENGTH_SHORT).show();
            return;
        }


        if(selected_item1.equals("Inches"))
        {
            if(selected_item2.equals("Kgs"))
            {
                bmi = (getWeight*10000f) / (2.54f*2.54f*getHeight * getHeight);

            }
            if(selected_item2.equals("Lbs"))
            {
                bmi = (getWeight*0.453592f*10000f) / (getHeight * getHeight*2.54f*2.54f);
            }

        }
        if(selected_item1.equals("Centimeters"))
        {
            if(selected_item2.equals("Kgs"))
            {
                 bmi = (getWeight*10000) / (getHeight * getHeight);
            }
            if(selected_item2.equals("Lbs"))
            {
                bmi=(getWeight*0.453592f*10000) / (getHeight * getHeight);
            }
        }
        mChart.setCenterText("BMI:"+df.format(bmi));
        mChart.invalidate();


    }


    @Override
    public void onBackPressed() {
            super.onBackPressed();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}
like image 847
Samarth Kejriwal Avatar asked Nov 21 '16 18:11

Samarth Kejriwal


1 Answers

For all chart types, you can set highlights programmatically by using highlightValue(float x, int dataSetIndex, boolean callListener).

In your case, you need to determine the BMI category index as this will give you the first parameter. Let's assume you did that and have the correct position stored in some variable categoryIndex.

The second parameter will always be zero as you only have one DataSet.

The third parameter should be false because you don't need to listen to any event, after all it's your code which is triggering the highlighting.

Now you can highlight the corresponding section of the chart like this:

public void calculate() {
    ...
    mChart.setCenterText("BMI:"+df.format(bmi));
    mChart.highlightValue(categoryIndex, 0, false);
    mChart.invalidate();
}

Note: There are several overloaded versions of highlightValue(), see also the documentation for MPAndroidChart

like image 73
Bö macht Blau Avatar answered Sep 20 '22 08:09

Bö macht Blau