<EditText
android:id="@+id/editText2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:maxLines="5"
android:lines="5">
</EditText>
User can input more than 5 lines, by pressing enter/next row key. How can I limit user input to fixed amount of rows with EditText?
Try using the following combination of attributes of the EditText inside the xml file:
android:singleLine="true"
android:maxLength="22"
You just need to make sure you have the attribute "inputType" set. It doesn't work without this line.
@Cedekasem you are right, there isn't a built in "row limiter". But I did built one my self, so if anyone is interested the code is below. Cheers.
I did something like you guys have been looking for. Here's my
LimitedEditText
class.Features:
won't bring you to the end - it will stay where have you been.
Im turning off listener, because every call of
setText()
method would recursively call these 3 callback methods in case when user exceeded characters or lines limit.Code:
I've made simpler solution for this :D
You can change the value of 3 in
txtSpecialRequests.getLineCount() > 3
to your needs.getLineCount() is one option; if you want non-zero values there make sure your view is measured. For soft keyboard onKeyListener won't work so you have to add addTextChangedListener() that will track text changes as you type. As soon as you get enough lines inside its call backs do whatever you want to limit it: delete characters with getText(), setText() or something more fancy. You can even limit the number of characters using a filter.
Another option is to monitor size of the text with getLineBounds(). This will interact with text gravity/paddign so be careful.