Android edittext key return goes to next text

2020-02-07 19:16发布

问题:

I have a series of EditText entries and would like it so when the user hits the enter key it will go to the next Editext. I know how do this one at a time but is there a way to tell all of the edittext controls to use the same function that checks the key entry and advances the cursor. It seems kind of crazy to have one function for each of the EditTexts

回答1:

Much simpler than sniffing keys: try setting android:singleLine="true" and android:imeOptions="actionNext" (at least for single-line entry textviews). Read more in the Android documentation for TextView.

Update: singleLine is deprecated now, but you can leave it out. It's the default behavior for editable text as long as you don't explicitly set android:inputType="textMultiLine", and inputType overrides the suggested singleLine replacement of maxLines="1" for editable text anyways.



回答2:

For an alternative or a newer approach for the answer given from Yoni...

Since singleLine is considereded deprecated, we can set manually to android:maxLines="1" with android:inputType="text".

Small explanation:

  • We use android:inputType="text" to specifically treat the input as plain text.
  • And we use android:maxLines="1" to set the max lines of the text to 1 (as it suggests).

Using maxLines="1" alone, will not cause any effect, but inputType="text" alone may work also, as Adam mentions (though I haven't checked this).



回答3:

Adding

    android:inputType="text"

in XML is just enough. When You are not defining input type, then it goes to next line.



回答4:

You could try adding a single event listener to all your editText objects:

OnKeyListener myKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
            // TODO: do what you got to do
            return false;
        }
    };
editText1.setOnKeyListener(myKeyListener);
editText2.setOnKeyListener(myKeyListener);
editText3.setOnKeyListener(myKeyListener);


回答5:

Apply this custom style in styles.xml

<style name="SingleLineText">
    <item name="android:inputType">text</item>
    <item name="android:maxLines">1</item>
</style>

and then set it in EditText like this

 style="@style/SingleLineText"


回答6:

Add the following lines in EditText

 android:singleLine="true"
 android:maxLines="1"