为我的 Android 制作一个简单的应用程序。
在我的xml界面中有一个文本框,用户将在其中输入一个数字(例如:10)。该文本框的id是“input1”
如何在java中调用input1的值并对其进行计算?
例如...
假设 input1 = x
x + 5 或 x*2
就此而言,如何让结果值在 UI 上的指定位置显示为不断更新的文本输出?
最佳答案
在使用此布局 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);
}
请注意,上述内容不包含错误处理:它假设您已将 input1
文本字段限制为仅允许输入整数。
关于java - 如何将 UI 中输入的值调用到 java 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2125052/