繁体   English   中英

当edittext android中的当前行为空时,如何防止用户换行?

[英]How to prevent user for going new line when the current line is empty in edittext android?

我有这个代码用于在我的编辑文本中打印项目符号和数字

XML 文件

<com.example.nutrifood.myEditText
            android:id="@+id/mealIngredientsInput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:cursorVisible="true"
            android:fontFamily="@font/hindmadurai_regular"
            android:gravity="top"
            android:inputType="textMultiLine"
            android:minLines="4"
            android:paddingStart="25dp"
            android:paddingEnd="20dp"
            android:textColor="@color/light"
            android:textSize="16sp" />

myEditText.java

公共类 myEditText 扩展 androidx.appcompat.widget.AppCompatEditText {

public Rect rect = new Rect();
public Paint paint = new Paint();
private myEditText editTextinput = findViewById(R.id.editTextinput);
boolean isTyping;

public myEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    
   ...

    editTextInput.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
            if (text.length() == 0) {
                isTyping = false;
                return;
            }            
            isTyping = true;
        }

     ...
    });
}

@Override
protected void onDraw(Canvas canvas) {
    if (isTyping) {
        int baseline = getBaseline();
        for (int i = 0; i < getLineCount(); i++) {
            canvas.drawText("  •", rect.left, baseline, paint);
            baseline += getLineHeight();
        }
    }
    super.onDraw(canvas);
}

}

这会给我这样的输出。

• 一

• 二

当前行为空时,有没有办法禁用键盘中的新行?

没有办法禁用键盘中的键,尤其是有条件的。 您可以在 xml 中使用数字,但所做的只是应用一个 textwatcher,它消除了不符合预期的更改,并且它不是有条件的。

你可以很容易地得到你想要的东西。 使用以下函数创建一个新的 TextWatcher:

void onTextChanged (CharSequence s, 
                int start, 
                int before, 
                int count) {
    String newText = s.toString().replace("\n\n","\n");
    if(newText.charAt(0) == '\n') {
        newText = newText.substring(1);
    }
    if(!s.toString().equals(newText)) {
       setText(newText);
    }
}

基本上,它会查找任何双换行符并将其替换为单个换行符。 然后它切断任何领先的换行符。 如果其中任何一个更改了字符串(如果找到其中任何一个),它会将文本设置为通过修复它们形成的新字符串。 如果不是,它将退出而不更改文本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM