当我在应用程序的“编辑”EditText字段中输入文本时,它不会按照 MoneyTextWatcher 进行格式化,但是我使的第二个条目格式化正确。关于发生了什么的任何想法?
我正在考虑重写这个,以便我可以使用私有变量,但每次尝试时我的应用都会崩溃。
public class addBills extends ListActivity {
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_add_bills);
Button btn = (Button) findViewById(R.id.btnAdd);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
edit.addTextChangedListener(new MoneyTextWatcher(edit));
EditText billName = (EditText) findViewById(R.id.billName);
list.add(billName.getText().toString() + " " + edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the add button */
btn.setOnClickListener(listener);
/** Setting the adapter to the ListView */
setListAdapter(adapter);
}
public class MoneyTextWatcher implements TextWatcher {
private final WeakReference<EditText> editTextWeakReference;
public MoneyTextWatcher(EditText editText) {
editTextWeakReference = new WeakReference<EditText>(editText);
}
@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 editable) {
EditText editText = editTextWeakReference.get();
if (editText == null) return;
String s = editable.toString();
if (s.isEmpty()) return;
editText.removeTextChangedListener(this);
String cleanString = s.replaceAll("[$,.]", "");
BigDecimal parsed = new BigDecimal(cleanString).setScale(2, BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR);
String formatted = NumberFormat.getCurrencyInstance().format(parsed);
editText.setText(formatted);
editText.setSelection(formatted.length());
editText.addTextChangedListener(this);
}
}
}
答案 0 :(得分:0)
从onCLick
EditText edit = (EditText) findViewById(R.id.txtItem);
edit.addTextChangedListener(new MoneyTextWatcher(edit));
将这些放在onCreate
方法内,但放在onClick