2016-12-05 94 views
0

我需要读取应用程序的条形码。我正在使用触发条形码扫描仪。通信是通过USB。当条形码扫描器读取条形码时,EditText焦点消失

如您所知,条形码扫描仪的工作方式与键盘类似。当设备读取条形码时,它会尝试将值写入具有焦点的输入。并且用户按下触发器,条形码扫描器将工作,直到 条形码被成功读取。然后它自己进入待机模式。阅读大量条形码的理想方式。

问题是,用户按下触发器并读取条形码后,EditText的焦点消失。焦点将随机在同一个布局中转到另一个视图。当用户试图再读取一个条形码时,操作失败,因为没有关注相关的EditText。

我试过了什么?

android:windowSoftInputMode="stateAlwaysVisible" 

添加上面的行到清单文件

android:focusable="true" 
android:focusableInTouchMode="true" 

以上对XML侧线加。

edtBarcode.setOnFocusChangeListener(new View.OnFocusChangeListener() 
    { 
     @Override 
     public void onFocusChange(View v, boolean hasFocus) 
     { 
      if (!hasFocus) 
      { 
       //find the view that has focus and clear it. 
       View current = getCurrentFocus(); 
       if (current != null) 
       { 
        current.clearFocus(); 
       } 

       edtBarcode.requestFocus(); 
      } 
     } 
    }); 

它检测EditText何时失去焦点。但我不能指定它。我确保EditText在触摸模式下可以聚焦。

我是如何解决它的?

handlerFocus = new Handler(); 
    final int delay = 1000; //milliseconds 

    handlerFocus.postDelayed(new Runnable() 
    { 
     public void run() 
     { 
      edtBarcode.requestFocus(); 
      handlerFocus.postDelayed(this, delay); 
     } 
    }, delay); 

我知道这个解决方案不好。那么,如何在不打开键盘的情况下始终将焦点留在同一个EditText中?

+0

什么时候的重点被改变了吗? –

+0

用户按下触发器并且条形码读取过程成功后。 –

回答

2

基本上当用户按下触发器时,它会触发EditText上的KeyEvent。基于扫描仪的配置,其可以是KEYCODE_TABKEYCODE_ENTER

所以我所做的就是听OnKeyEvent而不是OnFocusChange

试试这个:

edtBarcode.setOnKeyListener(new View.OnKeyListener() { 
     @Override 
     public boolean onKey(View v, int keyCode, KeyEvent event) { 
      if ((event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_ENTER) 
        || keyCode == KeyEvent.KEYCODE_TAB) { 
       // handleInputScan(); 
       new Handler().postDelayed(new Runnable() { 
         @Override 
         public void run() { 
          if (edtBarcode != null) { 
           edtBarcode.requestFocus(); 
          } 
         } 
       }, 10); // Remove this Delay Handler IF requestFocus(); works just fine without delay 
       return true; 
      } 
      return false; 
     } 
    }); 

希望这有助于〜

+0

最后一个字符是'\ n',意思是KEYCODE_ENTER。非常感谢,它的工作方式就像你上面发布的一样。 –

0

你能尝试:edtBarcode.setSelectAllOnFocus(true);

并隐藏,你可以试试这个键盘:Close/hide the Android Soft Keyboard

我希望我帮助。

+0

感谢您的答案,但它不起作用,仍然表现相同。 –