在Android開發(fā)中,經(jīng)常會用碰到這樣的需求:描述信息比較長,默認情況下只顯示幾行,點擊可以展開查看所有內(nèi)容,再次點擊有收起。
Android中沒有這樣的空間可以直接使用,所以本人對此進行封裝開源了一個可展開/收起的TextView,具體可以查看:ExpandCollpaseTextView
ExpandCollpaseTextView是可以展開和收起的文本控件
添加依賴:
- 在項目根目錄下的build.gradle添加如下依賴:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
- 在要使用的模塊目錄下的build.gradle添加如下依賴:
dependencies {
implementation 'com.github.jxiang112:ExpandCollapseTextView:v1.0.2'
}
特性:
- 可以設(shè)置收起狀態(tài)下顯示的行數(shù)
- 可以設(shè)置收起狀態(tài)下,最后一行剩余空白的占比
- 可以設(shè)置展開/收起按鈕:顯示的文字、字體顏色、字體大小
- 可以設(shè)置點擊展開和收起的事件源:全部文字的點擊事件都可以展開/收起、只有點擊展開/收起按鈕才可以展開收起
原理:
- 使用TextView的maxLine,收起的時候設(shè)置maxLine為多少行,展開時設(shè)置maxLine為Int的最大值
- 使用Paint的measureText來計算文本的寬度、行數(shù);如果測量的文本寬度、行數(shù)比設(shè)置的收起狀態(tài)下的行數(shù)小,則就不需要展開/收起功能;如果超過了收起狀態(tài)下的行數(shù),則會有展開/收起的功能,并計算收起狀態(tài)下最后一行能顯示的文字
屬性:
| 屬性名稱 | 屬性類型 | 屬性默認值 | 屬性描述 |
|---|---|---|---|
| expand_text | string | 展開>> | 展開按鈕顯示的文本 |
| collapse_text | string | 收起>> | 收起按鈕顯示的文本 |
| expand_text_size | integer | 14 | 展開/折疊文本字體大小,單位sp |
| expand_text_color | color | #00C25F | 展開/折疊文本顏色 |
| content_text | string | 文本內(nèi)容 | |
| text_line_height | dimension | 0 | 行高 |
| content_text_size | integer | 14 | 文本文字大小 |
| content_text_color | color | #333333 | 文本文字顏色 |
| collapse_show_line_number | integer | 2 | 折疊狀態(tài)下,顯示的行數(shù) |
| expand_state | enum | collapse | 設(shè)置展開折疊狀態(tài),collapse: 折疊狀態(tài);expend:展開狀態(tài) |
| collapse_line_space_percent | integer | 20 | 折疊狀態(tài)下,最后一行空白所占寬度的百分比,0-100 |
| expend_click_event_on | enum | all | 點擊可以展開/收起的事件源,all:點擊文本的任何地方都可以展開/收起;expand_text:只有點擊展開/收起按鈕才可以展開/收起 |
使用示例:
//xml布局文件中:
<com.wyx.components.widgets.ExpandCollpaseTextView
android:id="@+id/expand_textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:content_text_color="#999999"
app:content_text_size="12"
app:text_line_height="2dp"
app:expand_text_color="#06C362"
app:collapse_line_space_percent="70"
/>
//java文件中:
ExpandCollpaseTextView expandTextView = findViewById(R.id.expand_textview);
expandTextView.setText("XXXXXXXXXXXXXXXXXXX");
效果預(yù)覽:
image