如何覆盖 <ENTER>Android中虚拟键盘的按键行为

How to override the lt;ENTERgt; key behaviour of the virtual keyboard in Android(如何覆盖 lt;ENTERgt;Android中虚拟键盘的按键行为)
本文介绍了如何覆盖 <ENTER>Android中虚拟键盘的按键行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I want to override the behaviour of the ENTER key of the virtual keyboard so that:

  • 当屏幕上有更多字段时,它会制表"到下一个字段
  • 当它是屏幕的最后一个字段时,它执行屏幕的默认动作

我一直在使用 IME 选项和标签,但没有得到我想要的.有人有什么建议吗?

I've been playing with the IME options and labels, but just don't get what I want. Anybody have any suggestions?

推荐答案

在另一个论坛的帮助下,我找到了方法.

With help on another forum, I found the way to do it.

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

To make it reusable, I have created my own super dialog class that contains 2 OnKeyListener objects and an abstract submit method:

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 我可以使用这些对象来设置我的字段:

Now in the Dialog I can use these objects to set on my fields:

// 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);

这篇关于如何覆盖 <ENTER>Android中虚拟键盘的按键行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Android Mocking a Dagger2 injected dependency for a Espresso test(Android 为 Espresso 测试模拟 Dagger2 注入依赖项)
Mock object in Android Unit test with kotlin - any() gives null(使用 kotlin 在 Android 单元测试中模拟对象 - any() 给出 null)
How to mock Context using Mockito?(如何使用 Mockito 模拟上下文?)
Unit test Android, getString from resource(单元测试Android,从资源中获取字符串)
Mockito - what does verify method do?(Mockito - 验证方法有什么作用?)
Unit Testing in Retrofit for Callback(回调改造中的单元测试)