Android无EditText时获取扫描设备的扫描结果

  1. 无EditText时在Activity中增加以下内容即可获得扫描的结果
String barcode ="";
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getAction()==KeyEvent.ACTION_DOWN){
            Log.e(TAG,"dispatchKeyEvent: "+event.toString());
            char pressedKey = (char) event.getUnicodeChar();
            barcode += pressedKey;
        }
        if (event.getAction()==KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            Toast.makeText(getApplicationContext(),
                    "barcode--->>>" + barcode, Toast.LENGTH_LONG)
                    .show();

            qrEditText.setText(barcode);
            barcode="";
        }
        return super.dispatchKeyEvent(event);
    }
  1. 有EditText时通过以下方式获取:
etCode2.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    //扫描到的数据
                    String s = v.getText().toString().trim();

                    Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
                    //拿到数据后做其他操作

                    etCode2.setText(s);


                }
                return true;
            }

        });

你可能感兴趣的:(Android)