tags:

views:

73

answers:

2

Making a simple app for my android.

in my xml interface there is a text box in which the user will input a number (for example: 10). the id of this text box is "input1"

how do I call the value of input1 in java and then perform a calculation on it?

For example...

suppose input1 = x

x + 5 or x*2

and for that matter, how do I have the resulting value appear as constantly updated text output in a specified place on the UI?

+4  A: 

In the Activity where you are using this layout XML, you would do this:

private EditText input;
private EditText result;

public void onCreate(Bundle b) {
    setContentView(R.layout.my_activity);

    // Extract the text fields from the XML layout
    input = (EditText) findById(R.id.input1);
    result = (EditText) findById(R.id.result);

    // Perform calculation when input text changes
    input.addKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keycode, KeyEvent keyevent) {
            if (keyevent.getAction() == KeyEvent.ACTION_UP) {
                doCalculation();
            }
            return false;
        }
    });
}

private void doCalculation() {
    // Get entered input value
    String strValue = input.getText().toString;

    // Perform a hard-coded calculation
    int result = Integer.parseInt(strValue) * 2;

    // Update the UI with the result
    result.setText("Result: "+ result);
}

Note that the above includes no error handling: it assumes that you have restricted the input1 text field to allow the input of integer numbers only.

Christopher
I have a vague feeling there's a better way to determine text changes (such as when the user leaves the text field), but I haven't used it and couldn't see anything obvious in the API docs.
Christopher
+3  A: 

In your XML you can also set android:inputType="number" to only allow numbers as entries.

RickNotFred