EditText, OnKeyListener or TextWatcher (barcode scanning)

旧时模样 提交于 2019-12-12 13:13:02

问题


I'm using a barcode scanner which inserts barcode string into an EditText in this format "12345\n". Instead of using a search button, I want to trigger the search event by the "\n" character. I used TextEdit's addTextChangedListener and inside that function I'm doing:

protected TextWatcher readBarcode = 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) {
  // TODO Auto-generated method stub
  char lastCharacter = s.charAt(s.length() - 1);

  if (lastCharacter == '\n') {
   String barcode = s.subSequence(0, s.length() - 1).toString();
   searchBarcode(barcode);
  }
 }
};

It works pretty good for the first time, but I also want to clear the EditText after each scan. But it's not possible to do that inside afterTextChanged event because it's going into a recursive loop or something.

Here is the other solution, which is working pretty good:

editBarcode.setOnKeyListener(new OnKeyListener() {

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    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 what is the right way to do it it. Maybe I can use EditText's OnKeyListener event. Any suggestions?

Thanks


回答1:


If you clear the EditText content in the afterTextChanged(), you shouldn't have an infinite loop.

 @Override 
 public void afterTextChanged(Editable s) { 
  if (s.length > 0) {

      char lastCharacter = s.charAt(s.length() - 1); 

      if (lastCharacter == '\n') { 
       String barcode = s.subSequence(0, s.length() - 1).toString();
       myEditText.setString("");
       searchBarcode(barcode); 
      }
  } 



回答2:


Code of @Hrk does not work for me, because method myEditText.setString() does not exist.

Here is one way:

editText.addTextChangedListener(new TextWatcher() {

  ...

  @Override
  public void afterTextChanged(Editable s) {
    if (s.toString().trim().length() == 0)
      return;

    //do your work, then clear the text here
    s.clear();
  }
});


来源:https://stackoverflow.com/questions/4151499/edittext-onkeylistener-or-textwatcher-barcode-scanning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!