我想创建一个EditText,只接受数字,最多为4个数字,并且永远不会比填入4个数字时更窄(为空时不会收缩或扩展以容纳4个数字,因此它是固定的。)
前两个要求可以通过设置: android:inputType="number" 和 android:maxLength="4" 来实现。
如何设置最小长度?
答案:您可以使用以下代码来设置EditText的最小长度: android:minWidth="40dp" 其中40dp表示EditText的宽度,即使没有值,也应始终保持这个宽度。
我想创建一个EditText,只接受数字,最多为4个数字,并且永远不会比填入4个数字时更窄(为空时不会收缩或扩展以容纳4个数字,因此它是固定的。)
前两个要求可以通过设置: android:inputType="number" 和 android:maxLength="4" 来实现。
如何设置最小长度?
一个很少使用(据我所知)但你可以使用的EditText属性是:
android:ems="4"
这将使EditText的宽度恰好为4个字体单位。一个字体单位的宽度是选择字体中最宽字符(M)的宽度。
有点“hackish”,但是你可以将你的EditText
放在一个FrameLayout
里,同时再放一个text="0000"
且visibility=invisible.
的TextView
。FrameLayout
应该有width=wrap_content
,而你的EditText
将有width=match_parent
。
这样应该总是使它具有正确的宽度。
这种方法的好处是,它完全是XML侧面的,没有涉及到代码。
<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>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="000000"
android:textColorHint="#00FFFFFF"
android:maxLength="6"
android:inputType="numberPassword" />
这个解决方案与字体、字距和其他可能变化的事物无关。textColorHint 是一种 0% 不透明度的白色,因此提示永远不应该对用户可见。
你也可以尝试使用...
android:ems="4"
android:maxEms="4"
android:layout_width="wrap_content"
这会确保在默认的Android edittext样式下,尽可能地实现最紧密的拟合。
如果您需要更多关于左右填充的控制,您可以使用:
android:background="#ffffff"
android:paddingLeft="0dp"
android:paddingRight="0dp"
使用android:width="XXX.Xdp"
这可以让你以密度像素为单位设置宽度,应该相对于屏幕密度。我曾尝试使用基于ems的方法来设置一个宽度为2个字符的字段,但由于ems需要一个整数,2太小了,3太大了。很烦人。
myEditText.setLayoutParams(new LinearLayout.LayoutParams(200, 50));
不清楚是否有内置解决方案,但您可以尝试在提交时被动检查长度并弹出带有错误消息的对话框。
我使用android:layout_width="60dip",所以同意Mike Fratto的观点。
ems解决方案似乎也很有趣。
Phil
当您输入的字符超过EditText宽度时,可以设置对齐方式来增加宽度或EditText宽度。请设置上述视图的toLeftOf和toRightOf以管理这些内容。只有一个解决方案。