title: EditText, OnKeyListener or TextWatcher (barcode scanning)
body: <p>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:</p>
  
  <pre><code>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);
    }
   }
  };
  </code></pre>
  
  <p>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.</p>
  
  <p>Here is the other solution, which is working pretty good:</p>
  
  <pre><code>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 &amp;&amp; barcode.length() &gt; 0) {
          editBarcode.setText("");
          searchBarcode(barcode);
          return true;
      }
  
      return false;
  }
  });
  </code></pre>
  
  <p>Actually I'm not sure what is the right way to do it it. Maybe I can use EditText's OnKeyListener event. Any suggestions?</p>
  
  <p>Thanks</p>