Prevent enter key on EditText but still show the t

2019-01-16 13:29发布

How do I make an EditText on Android such that the user may not enter a multi-line text, but the display is still multi-line (i.e. there is word-wrap instead of the text going over to the right)?

It's similar to the built-in SMS application where we can't input newline but the text is displayed in multiple lines.

18条回答
疯言疯语
2楼-- · 2019-01-16 14:17
    EditText textView = new EditText(activity);
    ...
    textView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            if(KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode()) {
                return false;
            }
            ....... 

        }
    });
查看更多
ら.Afraid
3楼-- · 2019-01-16 14:18

You can set it from the xml like this:

android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="10"

don't forget android:inputType="text", if you don't set it, it doesn't work. I don't know why though. Also don't forget to change maxLines to your preferred value.

查看更多
乱世女痞
4楼-- · 2019-01-16 14:19

I would subclass the widget and override the key event handling in order to block the Enter key:

class MyTextView extends EditText
{
    ...
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode==KeyEvent.KEYCODE_ENTER) 
        {
            // Just ignore the [Enter] key
            return true;
        }
        // Handle all other keys in the default way
        return super.onKeyDown(keyCode, event);
    }
}
查看更多
聊天终结者
5楼-- · 2019-01-16 14:19

The accepted answer worked so well until I copied text with line-breaks into into the EditText. So I added onTextContextMenuItem to monitor the paste action.

@Override
public boolean onTextContextMenuItem(int id) {
    boolean ret = super.onTextContextMenuItem(id);
    switch (id) {
        case android.R.id.paste:
            onTextPaste();
            break;
    }
    return ret;
}

public void onTextPaste() {
    if (getText() == null)
        return;
    String text = getText().toString();
    text = text.replaceAll(System.getProperty("line.separator"), " ");
    text = text.replaceAll("\\s+", " ");
    setText(text);
}
查看更多
聊天终结者
6楼-- · 2019-01-16 14:20

You can change the action button from code

editText.imeOptions = EditorInfo.IME_ACTION_DONE
editText.setRawInputType(InputType.TYPE_CLASS_TEXT)

Xml

android:inputType="textMultiLine"
查看更多
等我变得足够好
7楼-- · 2019-01-16 14:22

Property in XML

android:lines="5"
android:inputType="textPersonName"
查看更多
登录 后发表回答