我正在为EditText字段添加一个监听器,以便实时将数字格式化为货币。
loanText.addTextChangedListener(new TextWatcher() {
private String current = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formated = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formated;
loanText.setText(formated);
loanText.setSelection(formated.length());
}
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
});
但是,当我尝试清除EditView字段时,我的应用程序将崩溃。此外,退格键不再起作用。
答案 0 :(得分:19)
问题是,您的TextWatcher
发现您正在“清除”文字,因此会向其回调方法(afterTextChanged
,beforeTextChanged
等)发送请求。< / p>
我所做的只是删除TextWatcher
,清除文字,然后将TextWatcher
添加回EditText
。这样,没有任何内容正在听我的EditText
更改。
您可能必须保留TextWatcher
的实例,而不是像您一样内联它。这样,您每次要清除EditText
loanText.removeTextChangedListener(yourTextWatcherObject);
loanText.setText("");
loanText.addTextChangedListener(yourTextWatcherObject);
答案 1 :(得分:4)
尝试使用
afterTextChanged
代替。我也遇到了另一个问题。
答案 2 :(得分:1)
我发现这个课对我很有用: http://www.java2s.com/Code/Android/UI/ConvertinputvaluetoCurrencyinTextWatcher.htm
希望能为你节省一些时间。
答案 3 :(得分:1)
public class MainActivity extends Activity {
EditText et;
TextWatcher tw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText) findViewById(R.id.et);
tw=new TextWatcher(){
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(tw);
et.setText(Math.random()+"");//add your logic here
et.addTextChangedListener(tw);
}};
et.addTextChangedListener(tw);
}
} 这是一个简单的解决方案。
答案 4 :(得分:-1)
您可以按如下方式检查onTextChanged中Text是否为空,如果为空则不执行任何操作
s.toString().isEmpty()
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current) && !s.toString().isEmpty()){
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formated = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formated;
loanText.setText(formated);
loanText.setSelection(formated.length());
}
}