我希望制作一个将一个单位转换为另一个单位的应用程序(比如货币)。所以它由2个编辑文本组成。一个用户输入值,另一个包含结果。现在,在这里,我没有使用“转换”按钮将值放在第二个编辑文本中,而是希望转换后的值出现在第二个编辑文本中,因为我输入的值是第一个。我怎样才能实现这一目标? 感谢
答案 0 :(得分:2)
为此使用TextWatcher
。将其设置在用户输入的EditText
上:
myEditText1.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
String value = s.toString();
// Perform computations using this string
// For example: parse the value to an Integer and use this value
// Set the computed value to the other EditText
myEditText2.setText(computedValue);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
}
});
修改1 :
检查空字符串""
:
myEditText1.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
String value = s.toString();
if (value.equals("")) {
myEditText1.setText("0");
// You may not need this line, because "myEditText1.setText("0")" will
// trigger this method again and go to else block, where, if your code is set up
// correctly, myEditText2 will get the value 0. So, try without the next line
// and if it doesn't work, put it back.
myEditText2.setText("0");
} else {
// Perform computations using this string
// For example: parse the value to an Integer and use this value
// Set the computed value to the other EditText
myEditText2.setText(computedValue);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(final CharSequence s, int start, int before, int count){
}
});