Home > database >  How to write exactly two lines in EditText?
How to write exactly two lines in EditText?

Time:03-22

I have created a TextInputEditText that allows you to take simple notes.

I have set maxlines="2" and inputType="textMultiLine" to write up to two lines.

However, when you start writing and there are two lines, the size of the view is set to fit the size of two lines, but you can continue to write text.

In other words, you can write more than 2 lines of text.

How can I solve this?


Normal

enter image description here

Write two lines (Increase view size to fit up to two lines)

enter image description here

Write more than two lines(scrollable)

enter image description here

XML*

<com.google.android.material.textfield.TextInputLayout
    style="@style/Custom.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_memo"
        android:inputType="textMultiLine"
        android:maxLines="2" />
</com.google.android.material.textfield.TextInputLayout>

CodePudding user response:

Unfortunately maxLines corresponds to the outer height of the Edit area not the actual text inside You might want to use TextWatcher method to limit typing to whatever amount of lines you want

    textInput.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            // find how many rows it cointains
            val editTextRowCount = textInput.lineCount
            if (editTextRowCount > 2) {
                textInput.text?.delete(textInput.selectionEnd - 1,textInput.selectionStart)
            }
        }
    })
  • Related