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

本文介绍了在Android中实现多行文本输入的方法,用户输入时不使用回车或换行符,但显示为多行文本。提供了四种不同的解决方案,包括重写EditText类、监听键盘事件和文本变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何在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, "");

            }


        }
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值