转载请注明出处:http://blog.csdn.net/zhangphil
Android可收缩/扩展的TextView【1】
在一些应用中,比如腾讯的应用市场APP应用宝,关于某款应用的介绍文字,如果介绍文字过长,那么不是全部展现出来,而是显示三四行的开始部分(摘要),预知全部的内容,用户点击展开按钮即可查阅全部内容。
这样的设计有一定的优越性,毕竟用户的时间有限,注意力和关注力也有限,在使用APP时候,用户需要在最短时间内尽可能快速浏览和查阅到更主要内容,而不是一大堆泛泛而谈的文字内容。
在Android原生的TextView的基础上,我自己写了一个可收缩/扩展的TextView:PhilExpandableTextView。
实现原理:核心是控制TextView的max lines。在TextView的初始化阶段但尚未绘制出View的时候,使用ViewTreeObserver,监听onPreDraw事件,获取TextView正常显示需要显示的总行数,但只给TextView设置最大运行的行数(小于总行数),从而造成TextView的收缩摘要效果,当用户通过按钮或其他方式扩展时候,把TextView的最大行数设置为正常显示完全的行数+1(+1是保持余量,避免不足)。
最终,如图,图1是收缩状态:
图2是当用户点击了Button按钮后展开后的状态:
给出测试及全部源代码。
测试的主Activity MainActivity.Java:
MainActivity.java需要的布局文件:
核心的PhilExpandableTextView.java: