我想从editText中获取整数,然后按下按钮,在textView中显示输入。问题是结果总是为零。在此先感谢您的帮助。
EditText editText = (EditText) findViewById(R.id.editText);
TextView textView = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
try{
String string = editText.getText().toString();
int num = Integer.parseInt(string);}
catch(NumberFormatException numb){
Toast.makeText(this, "Problem", Toast.LENGTH_SHORT).show();
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String number = String.valueOf(num);
textView.setText(number);
}
});
答案 0 :(得分:1)
您需要在onClick方法中读取EditText值以检索更新的值
EditText editText = (EditText) findViewById(R.id.editText);
TextView textView = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
String string = editText.getText().toString();
int num = Integer.parseInt(string); // retrieve the updated value
String number = String.valueOf(num);
textView.setText(number);
}
catch(NumberFormatException numb){
Toast.makeText(this, "Problem", Toast.LENGTH_SHORT).show();
}
}
});
答案 1 :(得分:0)
您必须在侦听器本身中执行所有值查找和计算。从我在这里看到的,当你最初设置“num”时,字符串是空的。