您好,登錄后才能下訂單哦!
兩個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;
}
做了好久才調通,希望能對同樣遇到這類困難的人!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。