如何在android中使用两个或多个文本更改侦听器

时间:2016-08-03 13:18:12

标签: android

我在android中创建转换计算器,例如http://173.199.129.149/~tiffinex/Dev/MTO/beta/index-calculator.php,但使用了一个文本更改侦听器。它运行正常。当我尝试使用两个或更多文本更改侦听器时,它不会给出响应,我的应用程序停止工作,代码如下所示,

et1 = (EditText)findViewById(R.id.editText);
et2 = (EditText)findViewById(R.id.editText2);
et3 = (EditText)findViewById(R.id.editText3);   

et1.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)    {
}

@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

if (et1.getText().toString().equals("")) {
    et2.setText("0");
    et3.setText("0");
    } else {
        String s1 = et1.getText().toString();
        Double d1 = Double.parseDouble(s1);
        Double d3 = d1 * 12;
        String s3 = Double.toString(d3);

        et2.setText(s3);
        Double d4 = d1 * 0.3048;
        String s4 = Double.toString(d4);
        et3.setText(s4);
        }
}

@Override
public void afterTextChanged(Editable editable) {}
});

et2.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int  i2) {
}

@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)   {

if (et2.getText().toString().equals("")) {
    et1.setText("0");
    et3.setText("0");
} else {
    String s1 = et2.getText().toString();
    Double d1 = Double.parseDouble(s1);
    Double d3 = d1 / 12;
    String s3 = Double.toString(d3);

        et1.setText(s3);
        Double d4 = d1 * 39.40;
        String s4 = Double.toString(d4);
        et3.setText(s4);
    }

@Override
public void afterTextChanged(Editable editable) {
}
});

et3.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2){
}

@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)      {

if (et3.getText().toString().equals("")) {
et2.setText("0");
et1.setText("0");
} else {
    String s1 = et3.getText().toString();
    Double d1 = Double.parseDouble(s1);
    Double d3 = d1 * 39.40;
    String s3 = Double.toString(d3);

    et1.setText(s3);
    Double d4 = d1 / 3.48;
    String s4 = Double.toString(d4);
    et3.setText(s4);
    }

@Override
public void afterTextChanged(Editable editable) {}
});
}

1 个答案:

答案 0 :(得分:0)

您遇到此问题是因为您还在wrapItemAndSub = <li class="first icon1">|</li>|*|<li class="icon2">|</li>|*|<li class="icon3">|</li>|*|<li class="icon4">|</li>|*|<li class="last iconN">|</li> 中设置了其他“EditText”,这基本上会触发TextWatcher来电的连锁反应。为了解决这个问题,我们可以确保只有当用户的当前焦点位于使用setText()的{​​{1}}时,我们才会触发TextWatcher回调。在您的代码中:

EditText