0

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

tadvas
  • 131
  • 1
  • 13

2 Answers2

1

You can limit your EditText height by number of lines properties, if it helps:

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:lines="2"
        android:maxLines="5"
        android:minLines="2" />

They are totally related to Fonts and also can be edited programatically:

editText.setLines(3);
editText.setMaxLines(5);
editText.setMinLines(2);
Mohsen Mirhoseini
  • 8,454
  • 5
  • 34
  • 59
0

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;
    }

    @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);
        }
    }
}
tadvas
  • 131
  • 1
  • 13