[英]how do you call a value entered in a UI to your java class?
Making a simple app for my android. 为我的android制作一个简单的应用程序。
in my xml interface there is a text box in which the user will input a number (for example: 10). 在我的xml界面中,有一个文本框,用户可以在其中输入数字(例如:10)。 the id of this text box is "input1" 此文本框的ID为“ input1”
how do I call the value of input1 in java and then perform a calculation on it? 如何在Java中调用input1的值,然后对其进行计算?
For example... 例如...
suppose input1 = x 假设输入1 = x
x + 5 or x*2 x + 5或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? 因此,如何使结果值作为不断更新的文本输出显示在UI上的指定位置?
In the Activity
where you are using this layout XML, you would do this: 在使用此布局XML的Activity
中,您将执行以下操作:
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. 请注意,以上内容不包含错误处理:它假设您已将input1
文本字段限制为仅允许输入整数。
在XML中,您还可以将android:inputType="number"
为仅允许数字作为条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.