如何覆盖Android </enter>中虚拟键盘的<enter>键行为

时间:2010-07-17 15:37:11

标签: android keyboard virtual

我想覆盖虚拟键盘的 ENTER 键的行为,以便:

  • 当屏幕上有更多字段时,它会“标记”到下一个字段
  • 当它是屏幕的最后一个字段时,它会执行屏幕的默认操作

我一直在玩IME选项和标签,但只是没有得到我想要的。有人有什么建议吗?

1 个答案:

答案 0 :(得分:9)

在另一个论坛的帮助下,我找到了实现目标的方法。

为了使其可重用,我创建了自己的超级对话框类,其中包含2个OnKeyListener个对象和一个抽象提交方法:

public abstract class MyAbstractDialog extends Dialog {

/**
 * OnKeyListener that puts the focus down when the ENTER key is pressed
 */
protected View.OnKeyListener onEnterFocusDown = new View.OnKeyListener() {

                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                            (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                v.requestFocus(View.FOCUS_DOWN);
                        return true;
                }
                        return false;
                }
        };

/**
 * OnKeyListener that submits the page when the ENTER key is pressed
 */
protected View.OnKeyListener onEnterSubmitView = new View.OnKeyListener() {

                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                            (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                submitView(v);
                        return true;
                }
                        return false;
                }
        };
        protected abstract void submitView(View v);

}

现在在Dialog我可以使用这些对象在我的字段上设置:

// make the ENTER key on passwordField1 put the focus on the next field
passwordField1.setOnKeyListener(onEnterFocusDown);

// make the ENTER key on passwordField2 submit the page
passwordField2.setOnKeyListener(onEnterSubmitView);