避免在EditText中输入回车键但文本依然是多行显示

如何在Android上设计一个这样的EditText:用户不用使用回车或换行符输入一个多行文本,但是文本显示依然是多行,即有自动换行。

方案一、

 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (event != null) {
   // if shift key is down, then we want to insert the '\n' char in the TextView;
    // otherwise, the default action is to send the message.
                if (!event.isShiftPressed()) {
                    if (isPreparedForSending()) {                        
                        //confirmSendMessageIfNeeded();
                        showDialog(SIM_CARD_CHOOSER_ID, null);
                    }
                    return true;
                }
                return false;
            }

方案二、

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);
    }
}
方案三、

使用以下这个方法你不用重写 EditText类。只需要使用空字符串捕捉然后替代换行符。

myEditTextObject.addTextChangedListener(new TextWatcher() {


        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        public void afterTextChanged(Editable s) {
            for(int i = s.length(); i > 0; i--){

                if(s.subSequence(i-1, i).toString().equals("\n"))
                     s.replace(i-1, i, "");

            }


        }
    });

猜你喜欢

转载自blog.csdn.net/jie1991liu/article/details/49779969