当条形码扫描器读取条形码时,EditText焦点消失

Bur*_*kir 1 android focus android-edittext

我需要读取应用程序的条形码。我为此使用了触发条码扫描器。通过USB进行通讯。

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

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

我尝试了什么?

android:windowSoftInputMode="stateAlwaysVisible"
Run Code Online (Sandbox Code Playgroud)

将以上行添加到清单文件

android:focusable="true"
android:focusableInTouchMode="true"
Run Code Online (Sandbox Code Playgroud)

在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();
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

它检测EditText何时失去焦点。但是我不能把它分配回来。我确保EditText在触摸模式下可聚焦。

我该如何解决?

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

    handlerFocus.postDelayed(new Runnable()
    {
        public void run()
        {
            edtBarcode.requestFocus();
            handlerFocus.postDelayed(this, delay);
        }
    }, delay);
Run Code Online (Sandbox Code Playgroud)

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

Jiy*_*yeh 5

基本上,当用户按下触发器时,它会触发KeyEvent您的EditText。根据扫描仪的配置,可以是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;
        }
    });
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助〜