安卓设置EditText回车不换行

安卓应用在处理输入时,有时候我们不希望输入框输入回车键(换行键),通常的做法是在xml文件中进行设置。EditText关于这块的属性有很多。

为了达到目的,我们似乎需要做两件事情,一个是设置输入框的行数为单行,二是对回车键的响应不表现在输入框的内容上。
关于行数的设置有很多属性。

lines,其表述如下:

 <!-- Makes the TextView be exactly this many lines tall. -->
 <attr name="lines" format="integer" min="0" />
 

maxLines,其表述如下:

<!-- Makes the TextView be at most this many lines tall.
When used on an editable text, the <code>inputType</code> attribute's value must be
combined with the <code>textMultiLine</code> flag for the maxLines attribute to apply. -->
<attr name="maxLines" format="integer" min="0" />

minLines,其表述如下:

<!-- Makes the TextView be at least this many lines tall.
When used on an editable text, the <code>inputType</code> attribute's value must be
combined with the <code>textMultiLine</code> flag for the minLines attribute to apply. -->
<attr name="minLines" format="integer" min="0" />

singleLine,其表述如下:

<!-- Constrains the text to a single horizontally scrolling line
instead of letting it wrap onto multiple lines, and advances
focus instead of inserting a newline when you press the enter key.

The default value is false (multi-line wrapped text mode) for non-editable text, but if
you specify any value for inputType, the default is true (single-line input field mode).

{@deprecated This attribute is deprecated. Use <code>maxLines</code> instead to change
the layout of a static text, and use the <code>textMultiLine</code> flag in the
 inputType attribute instead for editable text views (if both singleLine and inputType
are supplied, the inputType flags will override the value of singleLine). } -->
<attr name="singleLine" format="boolean" />

以上属性中,最直接的singleLine已经被标记为过时,不在考虑范围内。其中maxLinesminLines一般一起使用,来控制输入框可以接受的文本容量。lines精确控制文本的行数的。

因此,理论上maxLineslines都可以达到单行的效果。

但是在实际测试过程中,我们发现即使设置了单行属性,在输入回车时,文本还是会换行。

观察maxLines属性的说明,发现其一般配合inputType属性一起使用,事实上,真正可以完成不想赢换行也正是这个属性。

具体做法是:不必考虑单行属性(当然,设置了单行属性会给输入带来比较好的体验)。我们通过设置输入类型属性,来选择一些恰当的输入类型,就可以避开回车产生的换行问题。在这些属性中有一个多行属性textMultiLine是专门为多行输入服务的,这个是会响应回车键的。其他的类似textnumber都是可以避开回车键的。也就是说,只需要设置输入框的
inputType属性即可。

android:inputType="number"

该技巧在登录界面使用较多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值