简体   繁体   中英

how do you call a value entered in a UI to your java class?

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?

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.

在XML中,您还可以将android:inputType="number"为仅允许数字作为条目。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM