Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set maximum number of text lines for an EditText

Tags:

android

Is there a way of specifying the maximum numbers of lines for an EditText? By that I mean all the lines of text, not only the visible ones (as the android:maxLines attribute is described). The lines number must not be 1, so android:singleLine is not an option.

like image 208
Gratzi Avatar asked Jan 18 '12 14:01

Gratzi


2 Answers

<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1" />

You just need to make sure you have the attribute "inputType" set. It doesn't work without this line.

android:inputType="text"

like image 132
Brinda Rathod Avatar answered Sep 18 '22 23:09

Brinda Rathod


import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class EditTextLinesLimiter implements TextWatcher {
    private EditText editText;
    private int maxLines;
    private String lastValue = "";

    public EditTextLinesLimiter(EditText editText, int maxLines) {
        this.editText = editText;
        this.maxLines = maxLines;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        lastValue = charSequence.toString();
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (editText.getLineCount() > maxLines) {
            int selectionStart = editText.getSelectionStart() - 1;
            editText.setText(lastValue);
            if (selectionStart >= editText.length()) {
                selectionStart = editText.length();
            }
            editText.setSelection(selectionStart);
        }
    }
}

And then:

editText.addTextChangedListener(new EditTextLinesLimiter(editText, 2));
like image 41
NagRock Avatar answered Sep 18 '22 23:09

NagRock