我正在通过条形码扫描将数据输入到EditText中。在该EditText上,我已经使用Textwatcher类应用了addTextChangedListener。但它显示出一种奇怪的行为。它在第一次运行时正常工作,但从下一次开始就会进入递归循环。由于这个EditText的递归行为,我扫描的一个项目添加了三次。以下是我正在使用的代码。
EditText barcodeScanner =(EditText)findViewById(R.id.barcodeFocus);
TextWatcher textwatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
Log.d("@@@@", s.toString());
if (s.length() > 1) {
// TODO Auto-generated method stub
if(flag){
char lastCharacter = s.charAt(s.length() - 1);
if (lastCharacter == 'p') {
String barcode = s.subSequence(0, s.length() - 1).toString();
Log.d("Id before parsing", barcode);
int btnId = Integer.parseInt(barcode.trim());
getItemsInformation(btnId);
}
flag = false;
}
else
flag = true;
}
}
};
barcodeScanner.addTextChangedListener(textwatcher);
private void getItemsInformation(int btnId) {
ProductOptionsDbHandler productOptionDbHandler = new ProductOptionsDbHandler(this);
List<String> optionNames = productOptionDbHandler.getProductOptions(btnId);
Product productdetails = prodDbHand.getSelecteProductsDetails(btnId);
float price = productdetails.getProductPrice();
if(optionNames.size()>0 || price == 0){
Intent intent = new Intent(this,ItemPopUpTabActivity.class);
intent.putExtra("intVariableName", btnId);
intent.putExtra("itemPrice", price);
intent.putExtra("itemTax", productdetails.getTaxRate());
startActivity(intent);
barcodeScanner.removeTextChangedListener(textwatcher);
barcodeScanner.setText("");
barcodeScanner.addTextChangedListener(textwatcher);
}
else{
listofItemList.add(productdetails);
QtyOfItems.add(1);
ItemsPrice.add(price);
ItemsIds.add(productdetails.getProductId());
itemTaxRate.add(productdetails.getTaxRate());
addItemintocheckoutList(price,productdetails);
List<String> itemsOptions = new ArrayList<String>();
itemsOptionsIds.add(itemsOptions);
Variables.itemposition++;
barcodeScanner.removeTextChangedListener(textwatcher);
barcodeScanner.setText("");
barcodeScanner.addTextChangedListener(textwatcher);
}
}
条形码的输入格式类似于002p。我已经尝试过使用。
barcodeScanner.removeTextChangedListener(textwatcher);
barcodeScanner.setText("");
barcodeScanner.addTextChangedListener(textwatcher);
完成工作后,最终什么也没有改变。我已经尝试了一个与此类似的问题,是由某人在SO上提出的(条形码扫描)EditText、OnKeyListener或TextWatcher。请指导我哪里做错了。感谢您的任何帮助。