如何在不点击按钮的情况下获取两个EditText
中的值,求和,并将其显示为第三个EditText
?
到目前为止,这是我的代码
public class MainActivity extends Activity {
int a,b,c;
EditText fst= (EditText)findViewById(R.id.fstdgt);
EditText scnd= (EditText)findViewById(R.id.scnddgt);
EditText thrd= (EditText)findViewById(R.id.thrddgt);
View v;
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a=Integer.parseInt(fst.getText().toString());
b=Integer.parseInt(scnd.getText().toString());
c=a+b;
thrd.setText("" + c);
}
}
这不起作用。应用程序每次启动时都会崩溃。有没有人有任何建议?
答案 0 :(得分:0)
为两个输入编辑框添加textchange侦听器将解决您的问题。这就是我认为应该如何解决你的问题:
int a, b,c; String input_a = fst.getText().toString(); String input_b = scnd.getText().toString(); fst.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!input_a.isEmpty() && !intput_b.isEmpty()){ a = Integer.parseInt(input_a); b= Integer.parseInt(input_b); c = a+b; String answer_value= "" + c; thrd.setText(answer_value); } else thrd.setText(""); } @Override public void afterTextChanged(Editable s) { } }); //and you need to add TextChangeListener for your "scnd" editText as well. scnd.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!input_a.isEmpty() && !input_b.isEmpty()){ a = Integer.parseInt(input_a); b= Integer.parseInt(input_b); c = a+b; String answer_value= "" + c; thrd.setText(answer_value); } else thrd.setText(""); } @Override public void afterTextChanged(Editable s) { } });