目錄
image
前言
公司項目需要一個類似微信朋友圈文字展開收起的效果,為了方便一開始我在網上找類似的效果實現,結果發現代碼量都很多計算量很大,而我頭腦這么簡單所以看起來比較費勁因此我就用非常簡單的方法寫了一個自定義的展開收起控件。
效果展示
image
實現原理
原理很簡單,需要用3個TextView,其中一個是展示文字的,一個是用來計算文字的行數,一個是用來展開和收起的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 展示文字-->
<TextView
android:id="@+id/view_seemore_tvcontent"
android:textColor="#000"
android:maxLines="2"
android:ellipsize="end"
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- 占位置的隱藏,并且高度設置的很小,用來獲取行數-->
<TextView
android:id="@+id/view_seemore_tvlinecount"
android:textColor="#000"
android:visibility="invisible"
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="1dp"/>
<!-- 顯示更多和收起-->
<TextView
android:id="@+id/view_seemore_tv_seemore"
android:layout_marginTop="5dp"
android:text="查看更多"
android:textColor="#00f"
android:visibility="gone"
android:maxLines="2"
android:ellipsize="end"
android:textSize="15sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
然后需要在自定義控件的類中做相應的處理:
class SeeMoreView:FrameLayout {
//是否展開和收起的標記
private var mIsShowAll:Boolean = false
constructor(context: Context) : this(context,null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs,0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
){
View.inflate(context, R.layout.view_seemore,this)
initListener()
}
private fun initListener() {
//查看更多的點擊事件
view_seemore_tv_seemore.setOnClickListener {
if(mIsShowAll){
//這是收起的關鍵代碼,將最大行數設置為你想展示的最小行數即可
view_seemore_tvcontent.maxLines = 2
view_seemore_tv_seemore.text = "查看更多"
}else{
//這是查看更多的關鍵代碼,將最大行數設置一個大數即可
view_seemore_tvcontent.maxLines = 20
view_seemore_tv_seemore.text = "收起"
}
mIsShowAll = !mIsShowAll
}
//attachedToWindow之后執行操作
post {
//這里必須這樣寫,這是在attachedToWindow之后執行操作,否則獲取行數會出問題
Log.e("測試","OnLayout${view_seemore_tvlinecount.lineCount}")
if(view_seemore_tvlinecount.lineCount>2){
view_seemore_tv_seemore.visibility = View.VISIBLE
}else{
view_seemore_tv_seemore.visibility = View.GONE
}
}
}
/**
* 設置文字
*/
fun setText(text:String){
//每次設置文字后都要進行重置
view_seemore_tvcontent.text = text
view_seemore_tvlinecount.text = text
view_seemore_tv_seemore.text = "查看更多"
view_seemore_tvcontent.maxLines = 2
mIsShowAll = false
if(view_seemore_tvlinecount.lineCount>2){
view_seemore_tv_seemore.visibility = View.VISIBLE
}else{
view_seemore_tv_seemore.visibility = View.GONE
}
}
}