未经本人授权,不得转载!否则必将维权到底
这次版本迭代产品提出了一个很常见的需求:列表中的一个 TextView 条目默认展示两行文本,超过两行则展示一个 Button,可点击展开阅读。再次点击将文本折叠起来。可折叠的 TextView 网上教程很多,但找不到这种类似的。做这个需求又遇到一些坑,故记录一下,供后人参考,喜欢就直接 Ctrl + c/v。
#效果展示
#一、需求拆分
- 文本不满两行时,底部的展开按钮隐藏
- 文本超过两行,底部显示展开按钮,点击按钮文本展开/隐藏
- 记录展开/隐藏的状态,当该条目滑出屏幕可见范围或点击其他条目再返回时,展开/隐藏状态保持不变
前面两点很容易实现,重点在第三条。它很容易忽视,所以在第三步踩了点坑
#二、具体实现
由于该条目出现在列表中,所以我们将其抽取成一个自定义 View ,这样逻辑比较清晰,更加解耦。
- 布局(标题、正文、底部按钮)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<!-- 标题-->
<cn.keithxiaoy.TitleView
android:id="@+id/titleView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</cn.keithxiaoy.TitleView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:orientation="vertical"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="12dp">
<!--重点属性: lineSpacingExtra = 3dp 行间距 3 dp-->
<TextView
android:id="@+id/apply_school_desc_notice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="3dp"
android:padding="@dimen/default_padding"
android:textColor="@color/font_dark"
android:textSize="@dimen/font_si