I would like to create an EditText which accepts only numbers, has a maximum of 4 numbers, and is never narrower than it would be if filled with 4 numbers (does not shrink
Don't know about built-in solution but you can try passivly check the length and rise a dialog with error message at the moment of submission.
One rarely-used (AFAIK) attribute of an EditText that you can use is:
android:ems="4"
This makes the EditText exactly 4 ems wide. An em width is the width of the widest (M) character in the selected font.
You can also try using. . .
android:ems="4"
android:maxEms="4"
android:layout_width="wrap_content"
. . . this should insure the tightest fit possibly allowed by the default android edittext style
For additional control with the padding on both left and right you can use
android:background="#ffffff"
android:paddingLeft="0dp"
android:paddingRight="0dp"
The problem is, that an EditText widget can loss focus because of a lot of different actions like touching another sensitive view, menu button or (hard keyboard cursor control) and so on. The restiction of a maximum length or type of the input can be done during the tying process (accept the character if it passes the filter or the length is not exceeded). but focus lost can be occour every time - even the submission is not completed yet and the input to short -> therefore there is no build-in minimum length solution, because the application would block at this point the execution of another event or task. At least you have to validate your input before going to the next step in your workflow.
A little hackish, but you can put your EditText
inside a FrameLayout
alongside with another TextView
with text="0000"
and visibility=invisible.
FrameLayout
Should have width=wrap_content
and your EditText
will have width=match_parent
.
That should make it the right width always.
The advantage of this is, it's 100% xml-side, no code involved.
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0000"
android:visibility="invisible" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="4" />
</FrameLayout>
There is an incredibly easy way to do this programmatically.
myEditText.setLayoutParams(new LinearLayout.LayoutParams(200, 50));
This would set the width to 200 and the height to 50!!
Enjoy :)