I am using a barcode scanner that inserts a barcode line into an EditText in this format "12345 \ n". Instead of using the search button, I want to trigger a search event with the character "\ n". I used TextEdit addTextChangedListener and inside this function that I execute:
protected TextWatcher readBarcode = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
char lastCharacter = s.charAt(s.length() - 1);
if (lastCharacter == '\n') {
String barcode = s.subSequence(0, s.length() - 1).toString();
searchBarcode(barcode);
}
}
};
It works very well for the first time, but I also want to clear the EditText after each scan. But this cannot be done inside the afterTextChanged event, because it goes into a recursive loop or something like that.
Here is another solution that works pretty well:
editBarcode.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String barcode = editBarcode.getText().toString();
if (keyCode == KeyEvent.KEYCODE_ENTER && barcode.length() > 0) {
editBarcode.setText("");
searchBarcode(barcode);
return true;
}
return false;
}
});
Actually, I'm not sure if this is the right way to do this. Maybe I can use the EditText OnKeyListener event. Any suggestions?
thank