一、首先看一下singleLine的解释与用法
android:singleLine
Formats: boolean
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 maxLines instead to change the layout of a static text, and use the textMultiLine 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). }
SingleLine的简单解释:
没设置singleLine时,也就是默认false时,文字到达末尾时再输入字符会折行,变成多行。按下回车时,插入新行。
设置singleLine后,会限制文本成一行,可横向滚动。当你按下回车键时,会将焦点移向下一个组件。
SingleLine已被弃用:
- 对于静态文本,如TextView,请使用maxLines代替
- 对于可编辑的组件,如EditText,请使用inputType = “textMultiLine” 代替
singleLine默认为false,但若设置inputType属性为任意一个值,singleLine的值默认变为true。
二、singleLine弃用的处理
可以使用下面的方法替代singleLine:
<TextView
android:maxLines="1"
/>
<!-- 单行 -->
<EditText
android:inputType="text"
/>
<!-- 多行 -->
<EditText
android:inputType="textMultiLine"
/>
三、注意事项
实际使用中,如果TextView设置了固定宽高,此时只设置maxLines=1,当内容超出了组件大小,依然会换行显示。
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:maxLines="1"/>
配合 ellipsize 使用时,就没问题了:
<TextView
android:layout_width="200dp"
android:layout_height="40dp"
android:maxLines="1"
android:ellipsize="end"
/>