关注 安卓007 ,免费获取全套安卓开发学习资料
背景经常会遇到文字过长时,需要在结尾显示省略号,在此总结一下所有的设置方法。

一、如果控件独占一行

添加如下设置即可
android:ellipsize="end"
android:lines="1"
二、如果控件需要相对于其他控件保持固定的距离

除了上面的设置外,还需要想办法能确定控件的宽度.
下面这个例子,通过layout_alignParentLeft让控件居于父控件左侧,同时让控件居于后方控件左侧(避免覆盖后方控件).
样例代码:
<RelativeLayout xmlns:android="http:///apk/res/android"
android:layout_width="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_item_search_result_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/tv_distance"
android:ellipsize="end"
android:lines="1"
android:text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" />
<TextView
android:id="@+id/tv_distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:lines="1"
android:text="12345KM" />
</RelativeLayout>
三、如果上述两种方案不适用,可以设定固定宽度.
- 方法1: 宽度采用wrap_content,设置maxEms。注意:maxEms不是任意字符的数量,是相当于对应数量大写M宽度。如果输入abc这样的字符,就可以输入超过maxEms的数量值。
android:layout_width="wrap_content"
android:maxLines="1"
android:ellipsize="end"
android:maxEms="5"
- 方法2: 宽度采用wrap_content,设置maxWidth,超过此值,则显示省略号
android:layout_width="wrap_content"
android:maxLines="1"
android:ellipsize="end"
android:maxWidth="70dp"
- 方法3: 设置layout_width为固定值。这种方式对比maxWidth的缺点是,无论textview实际由多少内容,都会占用这么大的地方。
android:layout_width="70dp"
android:maxLines="1"
android:ellipsize="end"
















