bug-a-lot 的解决方案很有趣——我没想过要使用优先级。相反,我利用了事件过程的不同阶段。对我来说,问题是决定箭头键是否应该在给定的文本字段中前进或后退一个字符,或者跳转到表单中的下一个或上一个字段。
首先,我覆盖了舞台对键的事件处理:
stage.addEventListener(KeyboardEvent.KEY_UP, typing);
// Sneak in before the normal processing handles right and left arrow keystrokes.
stage.addEventListener(KeyboardEvent.KEY_DOWN, pretyping, true, 10);
请注意,我将处理每个键两次 - 在系统执行之前它是魔法(在 KEY_DOWN 之前调用预输入),所以我可以在 Flash 移动它之前和系统处理它之后查看插入符号的位置(键入,在 KEY_UP 之后调用) .
/** Capture prior state of text field so we can later tell if user should tab to next field or previous field. */
private function pretyping(evt:KeyboardEvent):void {
var keyString:String = Configuration.getKeyString(evt);
if (isFocusInTextBox()) {
var tf:TextField = getFocus() as TextField;
capturePhaseCaret = tf.caretIndex;
}
}
getKeyString 是我的一种方法——它所做的只是将这些代码变成方便的助记符。isFocusInTextBox 是对我的焦点管理器的调用 - 我替换了标准焦点管理器以克服其他 Flash 问题。我只需要知道这个东西是否是一个文本字段。
接下来我必须在 Flash 已经移动插入符号甚至可能跳转到一个新字段之后处理密钥,并通过查看先前的状态,决定 Flash 做了什么并撤消它,然后做应该发生的事情。我的函数“打字”有很多本次讨论不需要的东西,但它所做的重要事情是调用allowKeyMapping。allowKeyMapping 决定用户是从文本字段中的最后一个字符位置输入向前箭头(或向下箭头),还是从开头输入向后箭头。如果是这样,“打字”将分别跳到下一个或上一个字段。
/** Prefer default behavior and do not allow certain kestrokes to be reinterpreted by key mappings, such as left and right cursor keys in text boxes. */
private function allowKeyMapping(keyString:String) {
var allow:Boolean;
// If focus is in a text field, allow right arrow to advance to next field only if caret is at end of text.
// Conversely, allow left arrow to back up to previous field only if caret is at beginning of text.
// The trick is that the normal processing of keystrokes by TextFields occurs before this method is called,
// so we need to know the caret position from before the key was pressed, which we have stored in capturePhaseCaret, set in pretyping.
if (isDragging) {
allow = false;
}
else if (isFocusInTextBox()) {
var tf:TextField = getFocus() as TextField;
if (keyString == Configuration.LEFT_CURSOR_KEY) {
allow = tf.caretIndex == 0 && capturePhaseCaret == 0;
}
else if (keyString == Configuration.RIGHT_CURSOR_KEY) {
allow = tf.caretIndex == tf.text.length && capturePhaseCaret == tf.text.length;
}
else {
allow = true;
}
}
else {
allow = true;
}
return allow;
}
对不起,我没有准备一个紧凑的例子。我只是认为重要的是要强调,无论你是否希望它们发生,你都可以绕过 Flash 为你做事的偏好。