两个EditText,其中一个值发生改变,另一个随之改变,这种效果一点没做好,两个EditText就会在TextWatcher方法中陷入死循环,下面是我自己写的一些代码:
text1 = (EditText) this.findViewById(R.id.edit1);
text2 = (EditText) this.findViewById(R.id.edit2);
textEN = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
text2.removeTextChangedListener(textTS);
//设置输入的数字为两位小数
if (s.toString().contains(".")) {
if (s.length() - 1 - s.toString().indexOf(".") > 2) {
s = s.toString().subSequence(0,
s.toString().indexOf(".") + 3);
text1.setText(s);
text1.setSelection(s.length());
}
}
if (s.toString().trim().substring(0).equals(".")) {
s = "0" + s;
text1.setText(s);
text1.setSelection(2);
}
if (s.toString().startsWith("0")
&& s.toString().trim().length() > 1) {
if (!s.toString().substring(1, 2).equals(".")) {
text1.setText(s.subSequence(0, 1));
text1.setSelection(1);
return;
}
}
//设置EditText的内容
if(!text1.getText().toString().trim().equals("") &&
null != text1.getText().toString().trim()){
s1 = text1.getText().toString().trim();
n1 = Float.parseFloat(s1);
}
text2.setText(getNumber2()+"");
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
text2.addTextChangedListener(textTS);
}
};
textTS = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
text1.removeTextChangedListener(textEN);
if (s.toString().contains(".")) {
if (s.length() - 1 - s.toString().indexOf(".") > 2) {
s = s.toString().subSequence(0,
s.toString().indexOf(".") + 3);
text2.setText(s);
text2.setSelection(s.length());
}
}
if (s.toString().trim().substring(0).equals(".")) {
s = "0" + s;
text2.setText(s);
text2.setSelection(2);
}
if (s.toString().startsWith("0")
&& s.toString().trim().length() > 1) {
if (!s.toString().substring(1, 2).equals(".")) {
text2.setText(s.subSequence(0, 1));
text1.setSelection(1);
return;
}
}
if(!text2.getText().toString().trim().equals("") &&
null != text2.getText().toString().trim()){
s2 = text2.getText().toString().trim();
n2 = Float.parseFloat(s2);
}
text1.setText(getNumber1()+"");
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
text1.addTextChangedListener(textEN);
}
};
text1.addTextChangedListener(textEN);
text2.addTextChangedListener(textTS);
private float getNumber1(){
return n-n2;
}
private float getNumber2(){
return n-n1;
}
做了好久才调通,希望能对同样遇到这类困难的人!
原文:http://9353753slq.blog.51cto.com/9343753/1638280