public class BarCodeKeyEventHelper {
private static final String TAG = BarCodeKeyEventHelper.class.getSimpleName();
private KeyListener mKeyListener;
private Editable mEditable;
private OnBarCodeListener mOnBarCodeListener;
public BarCodeKeyEventHelper(OnBarCodeListener onBarCodeListener) {
mKeyListener = new TextKeyListener(TextKeyListener.Capitalize.NONE, false);
mEditable = Editable.Factory.getInstance().newEditable("");
mOnBarCodeListener = onBarCodeListener;
}
/**
* 在Activity或者Fragment调用此监听函数即可
*
* @param event 事件
* @return 是否消费事件
*/
public boolean dispatchKeyEvent(KeyEvent event) {
return keyListener.onKey(null, event.getKeyCode(), event);
}
private View.OnKeyListener keyListener = new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
boolean result;
if (event.getAction() == KeyEvent.ACTION_DOWN)
result = mKeyListener.onKeyDown(null, mEditable, keyCode, event);
else if (event.getAction() == KeyEvent.ACTION_UP) {
if (event.getKeyCode() == KEYCODE_DPAD_DOWN) {
//内容结束,获取识别到的内容
RYLogUtils.d(TAG, "keyListener --> 识别结束,识别的 code = " + mEditable.toString());
if (mOnBarCodeListener != null) {
mOnBarCodeListener.onBarCodeDone(mEditable.toString());
}
mEditable.clear();
}
result = mKeyListener.onKeyUp(null, mEditable, keyCode, event);
} else {
result = mKeyListener.onKeyOther(null, mEditable, event);
}
return result;
}
};
public interface OnBarCodeListener {
void onBarCodeDone(String code);
}
}
网友评论