tadvas tadvas - 1 year ago 226
Android Question

Autofit EditText for Android

I have EditText with height, which depends on the device

User writes his or her text and I want to limit EditText by the height (number of symbols). Height can't be a constant, as a solution I can change size of a font

Are there any best practices, did anybody face this issue?

The only one good solution, I've already found is https://github.com/ViksaaSkool/AutoFitEditText

Answer Source

I found the right way to solve the issue - need to create a Listener, as Mohsen said:

EditText.addTextChangedListener(new EditTextLinesLimiter(EditText, 4));

And a class will be a following:

import android.content.Context;
import android.icu.text.StringSearch;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

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;

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

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


    public void afterTextChanged(Editable editable) {

        if (editText.getLineCount() > maxLines) {

            int selectionStart = editText.getSelectionStart() - 1;

            if (selectionStart >= editText.length()) {

                selectionStart = editText.length();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download