簡體   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