2016-12-05 56 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

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