在另一个活动或片段上使用集成条码扫描器时,为什么仍会在先前的活动/片段上触发 TextChanged 侦听器?

问题描述

我正在为主要使用集成了霍尼韦尔扫描仪的 NOMU T20 设备的客户开发 Android 应用。

我正在使用虚拟键盘将 TextWatcher 添加到 EditText,该键盘显示扫描的条形码并触发对 API 端点的调用(使用和结束字符“\n”)。如果我不导航到另一个活动或片段,它就可以正常工作。

问题是一旦我完成当前活动(又名“Act1”)并使用另一个带有自己的 TextWatcher 的 EditText 导航到另一个活动(又名“Act2”),然后再次扫描它会触发两个 TextWatcher,第一个来自“Act1” ”,最后来自“Act2”。这意味着当我只想为 Act2(当前活动)调用第二个 API 端点时,我需要额外调用一个 API 端点。

这个问题也可以用片段重现。

我尝试使用这个使用广播接收器的库 -> https://github.com/hjgode/IntentAPISample_by_HW 没有成功,我没有得到任何数据。

重现问题的代码(仅使用集成扫描仪而非外部扫描仪)

在来自活动的 EditText 上添加一个 TextChangedListener:

edit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s,int start,int count,int after) {

        }

        @Override
        public void onTextChanged(CharSequence s,int before,int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if (s.toString().trim().length() == 0)
                return;

            if (s.length() > 0) {

                char lastCharacter = s.charat(s.length() - 1);

                if (lastCharacter == '\n' || lastCharacter == '\r') {
                    String barcode = s.subSequence(0,s.length() - 1).toString();
                    edit.setText("");                       
                    Toast.makeText(MainActivity.this,barcode,Toast.LENGTH_LONG).show();
                    Log.e("MainActivity",barcode);
                }
            }
        }
    });

在 Act2 扫描时,我在终端中得到了这个日志。我试图找出“I/song”和“I/song-view”消息。

    I/song: hava scan message androidx.appcompat.widget.AppCompatEditText{9895392 VFED..CL. .F....ID 206,467-515,558 #7f080097 app:id/edit_barcode}
I/song-view: hava scan message 0
E/MainActivity: HORAE
I/song: hava scan message androidx.appcompat.widget.AppCompatEditText{fc384f3 VFED..CL. .F...... 206,558 #7f080098 app:id/edit_barcode2}
I/song-view: hava scan message 0
E/Act2: HORAE
D/WindowClient: Add to mViews: android.widget.LinearLayout{9fd1546 V.E...... ......I. 0,0-0,0},this = android.view.WindowManagerGlobal@ff7017e
D/ViewRootImpl[Toast]: hardware acceleration = true,fakeHwAccelerated = false,sRendererdisabled = false,forceHwAccelerated = false,sSystemRendererdisabled = false
D/Surface: Surface::connect(this=0x8d7d9000,api=1)
D/Surface: Surface::allocateBuffers(this=0x8d7d9000)
D/WindowClient: Add to mViews: android.widget.LinearLayout{1653fd2 V.E...... ......I. 0,sSystemRendererdisabled = false
D/Surface: Surface::allocateBuffers(this=0x8bf1c000)
D/Surface: Surface::connect(this=0x8bf1c000,api=1)

如果有人知道解决此问题的任何方法,我将不胜感激 提前致谢

解决方法

我通过删除“onStop/onDestroy”生命周期方法上的 TextWatcher 解决了这个问题。

第 1 步:实现我自己的 TextWatcher -> MyTextWatcher

第 2 步:在两个 Activity 上实例化 MyTextWatcher 并将其附加到 EditText

addTextChangedListener(mTextWatcherObj)

第 3 步:移除监​​听器

removeTextChangedListener(mTextWatcherObj);

谢谢