I am trying to sort a calculator app out in android. I have the layout set out fine and now I just need to do the code that will calculate. The app needs to show the number when it is pressed, then if say the + button is pressed it will store the first number, clear it off the screen, get a second number and then add them together. When the equal button is pressed it needs to show the results.
So far I have
public class Calculator extends Activity {
public EditText display;
TextView screen;
int a, result;
int c;
Button b1;
int sum1, sum2;
String r;
public int getSum1(int sum1) {
return sum1;
}
public int getSum2(int sum2) {
return sum2;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void buttonEventHandler(View v) {
screen=(EditText)findViewById(R.id.screen);
b1=(Button)findViewById(R.id.button1);
switch(v.getId()) {
case R.id.button1 :
screen.setText(screen.getText() + "1");
c = +1;
break;
case R.id.button2 :
screen.setText(screen.getText() + "2");
c = +2;
break;
case R.id.button3 :
screen.setText(screen.getText() + "3");
c = +3;
break;
case R.id.button4 :
screen.setText(screen.getText() + "4");
c = +4;
break;
case R.id.button5 :
screen.setText(screen.getText() + "5");
c = +5;
break;
case R.id.button6 :
screen.setText(screen.getText() + "6");
c = +6;
break;
case R.id.button7 :
screen.setText(screen.getText() + "7");
c = +7;
break;
case R.id.button8 :
screen.setText(screen.getText() + "8");
c = +8;
break;
case R.id.button9 :
screen.setText(screen.getText() + "9");
c = +9;
break;
case R.id.button0 :
screen.setText(screen.getText() + "0");
c = +0;
break;
case R.id.buttonC :
screen.setText(screen.getText() + "");
c = 0;
break;
case R.id.buttonPlus :
case R.id.buttonEquals :
}
}
}
How to do calculations?
Set your
sum1to zero inonCreate. When the user taps+, do:ctosum1sum1cto zero so a new number can be typedWhen the user taps
=, do:ctosum1sum1candsum1to zeroThis allows you to tap
4 + 5 + 6 =and see15, for example.