开发者

How to override the <ENTER> key behaviour of the virtual keyboard in Android

开发者 https://www.devze.com 2023-01-07 13:01 出处:网络
I want to override the behaviour 开发者_JAVA百科of the ENTER key of the virtual keyboard so that:

I want to override the behaviour 开发者_JAVA百科of the ENTER key of the virtual keyboard so that:

  • when there are more fields on the screen, it 'tabs' to the next field
  • when it is the last field of the screen, it performs the default action of the screen

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.

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

}

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

精彩评论

暂无评论...
验证码 换一张
取 消