tags:

views:

308

answers:

2

Hi,

I am a rookie to android. I am thinking of implementing a simple calculator in android to get a hold of the basics in android. I want to display a keypad with numbers and mathematical operations and when the user presses the keys the corresponding number is displayed in edit text. I tried using gettext() and updating the contents of edit text but it shows just the contents of pressed button. Also how do I read the contents of button so as to do mathematical operations in code? Any help would be much appreciated.

regards,

Primal

+1  A: 

Treating the caption of the button as the actual data is something that is pretty much only acceptable practice when you're doing the digit-buttons in a calculator, so I don't know if that holds for 'android basics' ;)

Regardless;

You're stating you want to display the corresponding number, when the user presses a key (button?). And then you say getText just shows you the content of the pressed button... Is that not exactly what you're asking for? You might need to provide a bit of code and show us what's not working the way you intended. But if a button has the text '8', and you want to treat that as an eight in mathematical operations, you need to parse it:

Integer myNumber = Integer.parse(myButton.getText());

...which will of course throw an exception if the text of myButton does not resolve to an integer.

EDIT, AS OF COMMENT

From the explanation of your problem you gave in your comment, yes, setText() resets the text entirely to the value it's being passed, but you can use a combination of that and getText() if you just want to append something to the current value:

myEditText.setText( myEditText.getText() + " " + myButton.getText() );
David Hedlund
I couldn't think of any other application :( Any suggestions in this aspect are welcome too :)getText() gives me what I want. The problem is I don't know how to populate an EditText using it. The only method I know is setText() and it refreshes the contents of EditText upon each button click.
primalpop
alright, see my update =)
David Hedlund
+3  A: 

To set the contents of an EditText:

EditText text = (EditText) findViewById(R.id.your_text);
text.setText("Display this text");

Instead of trying to pull the text off of your buttons and use it as an integer, I would just add a click listener to each one that "knows" the value of its button:

Button button = (Button) findViewById(R.id.num_1);
button.setOnClickListener(new View.OnClickListener() {
    @Override public void onClick(View v) {
        // Do something with the value of the button
    }
});
Erich Douglass