Android开发中我们经常会遇到一段文字(比如昵称)后跟着一些认证图标或者认证文字的场景,如果文字较短的时候不会出现问题,如下图
![](https://img.haomeiwen.com/i15284040/1dd0ca61e619b579.png)
![](https://img.haomeiwen.com/i15284040/16358a5b34eddb54.png)
当文字较长时候需要截断文字但是图标可以完整显示,这就有一定难度,如下图,可能需要自定义控件进行复杂的计算又或者给文字设置最大宽度,效果往往不尽如人意,而且耗费了大量时间。
![](https://img.haomeiwen.com/i15284040/e10b7fc16ae047e1.png)
本文将介绍一种简单解决该问题的方法。相信TableLayout大家在开发中几乎不会用到,不过用来解决该问题将达到事半功倍的效果。
一个TableLayout代表一个表格,TableRow代表一行,TableRow中添加几个View代表有多少列。所以你可以利用tablelayout中的shrinkColumns属性对某一列进行压缩。
<TableLayout
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:shrinkColumns="0">
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:ellipsize="end"
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="我是一个很长很长很长很长很长很长的名字" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#f00"
android:padding="3dp"
android:singleLine="true"
android:text="tag" />
</TableRow>
</TableLayout>
如上代码所示,我们将第0列也就是昵称那一列设置成可收缩,然后你就惊喜地发现你要的效果完成啦。是不是比你写自定义控件简单多了!
网友评论