kotlin安卓开发请帮我实现,文字如果超出两行则在尾部显示 “全部”,点击展开全部文字,再点击收缩文字,不够两行则正常展示
时间: 2024-02-28 19:55:10 浏览: 31
好的,这个需求可以通过自定义一个TextView来实现。以下是实现的伪代码:
```
class ExpandableTextView(context: Context, attrs: AttributeSet?) : androidx.appcompat.widget.AppCompatTextView(context, attrs) {
private val MAX_LINES = 2 // 最大行数
private var isExpanded = false // 是否展开
private var originalText: CharSequence? = null // 原始文本
private val expandText = "全部" // 展开文本
private val collapseText = "收缩" // 收缩文本
init {
setOnClickListener {
toggle()
}
}
private fun toggle() {
isExpanded = !isExpanded
setText(originalText, isExpanded)
}
fun setText(text: CharSequence?, expanded: Boolean = false) {
originalText = text
val spannable = if (expanded) {
SpannableString("$text $collapseText")
} else {
val layout = layout
if (layout == null || layout.lineCount <= MAX_LINES) {
SpannableString(text)
} else {
val end = layout.getLineEnd(MAX_LINES - 1)
val trimmedText = text?.subSequence(0, end)?.trimEnd()
SpannableString("$trimmedText... $expandText")
}
}
setText(spannable, BufferType.SPANNABLE)
}
}
```
在布局文件中使用ExpandableTextView代替TextView即可:
```
<com.example.myapp.ExpandableTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这里是需要展开的长文本,如果超过两行则在尾部显示全部,并且可以点击展开和收缩。" />
```
希望这可以帮到你!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)