0

I have a problem in java.

package apa.y;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;



public class myprice extends Activity  {
    /** Called when the activity is first created. */


    CheckBox book,pencil;
    TextView total;
    int sum=0;

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mymain);
    pencil = (CheckBox) findViewById(R.id.pencil);
    book = (CheckBox) findViewById(R.id.book);
    total = (TextView) findViewById(R.id.total);

    }

    public void onClick(View v) {

        sum = 0;
        if (pencil.isChecked()) {sum += 10;}else{sum +=0;}
        if (book.isChecked())   {sum += 5;}else{sum +=0;}

        total.setText("Total: "+sum);

    }
}

If book and pencil are checkbox and 1 textview, how to sum it? My existing code didn't work.

Aleks G
  • 56,435
  • 29
  • 168
  • 265

2 Answers2

1

What are you clicking on? The checkboxes? Then you need some kind of listener for those views. Two options are provided here: Android: checkbox listener

If you want to use the onClick method as you have it now, change this:

public class myprice extends Activity implements OnClickListener  {

And make sure that you set the OnClickListener for both checkboxes:

pencil = (CheckBox) findViewById(R.id.pencil);
pencil.setOnClickListener(this);
book = (CheckBox) findViewById(R.id.book);
book.setOnClickListener(this);
Community
  • 1
  • 1
Vincent Ketelaars
  • 1,069
  • 1
  • 14
  • 35
0

Create an OnCheckedChangeListener and set it to all your CheckBox. then on check box checked +1 in an Integer variable and on unchecked -1 from Integer variable. Now you have the latest total sum value of check boxes in your Integer variable.

You can do something like this :

int mCheckSum = 0;

private OnCheckedChangeListener dmCheckChangeListener = new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (isChecked) {
            mCheckSum += 1;
        } else if (isChecked == false) {
            if (mCheckSum > 0) {
                mCheckSum -= 1;
            }
        }

    }
};
Vipul Purohit
  • 9,807
  • 6
  • 53
  • 76