EditText上,OnKeyListener或TextWatcher(巴code扫描) [英] EditText, OnKeyListener or TextWatcher (barcode scanning)

查看:288
本文介绍了EditText上,OnKeyListener或TextWatcher(巴code扫描)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是吧code扫描器插入栏code字符串转换成一个EditText此格式12345 \\ N。而不是使用一个搜索按钮,我想用\\ n字符触发事件的搜索。我用文本编辑的addTextChangedListener和函数中我做的:

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);
  }
 }
};

它的工作原理pretty良好的第一次,但我也希望每次扫描后清除的EditText。但是,这是不可能做到这一点afterTextChanged事件中,因为它进入一个递归循环或东西。

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.

下面是其他的解决方案,这是工作pretty好:

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;
}
});

其实我不知道是什么做的正确方法。也许我可以使用的EditText的OnKeyListener事件。有什么建议?

Actually I'm not sure what is the right way to do it it. Maybe I can use EditText's OnKeyListener event. Any suggestions?

感谢

推荐答案

如果您清除了afterTextChanged的内容的EditText,你不应该有一个无限循环。

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

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

这篇关于EditText上,OnKeyListener或TextWatcher(巴code扫描)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆