-4

我有这个代码:

    final EditText kcalh=(EditText) findViewById(R.id.kcalh_inserisci);
    final EditText kw=(EditText) findViewById(R.id.kw_inserisci);
    kcalh.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
        public void afterTextChanged(Editable arg0) {
            int risultato=Integer.parseInt(kcalh.getText().toString())/860;
            kw.setText(""+risultato);
        }
        public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {}
     });
    kw.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
        public void afterTextChanged(Editable arg0) {
            int risultato=Integer.parseInt(kw.getText().toString())*860;
            kcalh.setText(""+risultato);
            System.out.println(risultato);
        }
        public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {}
     });

当我更改第一个edittext时,一切正常(第二个edittext改变了它的值......当我使用第二个时,应用程序崩溃了。你知道为什么吗?我认为它进入了第一个和崩溃的后文本......但是为什么不中二也?

4

1 回答 1

0

在将 String 解析为 Integer 之前检查 EditText 是否为空:

kw.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
        public void afterTextChanged(Editable arg0) {
            if(kw.getText().toString().length() > 0){
              int risultato=Integer.parseInt(kw.getText().toString())*860;
               kcalh.setText(""+risultato);
               System.out.println(""+risultato);
           }
        }
        public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {}
     });
于 2012-12-04T13:52:10.683 回答