看到一篇文章用到了一個佈局的屬性animateLayoutChanges
就能實現展開和收縮效果,特意記錄一下
效果
代碼
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestMainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:paddingVertical="16dp"
app:layout_constraintTop_toTopOf="parent"
+ android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:id="@+id/tvOpen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="點擊展開"/>
<TextView
app:layout_constraintTop_toBottomOf="@id/tvOpen"
app:layout_constraintStart_toStartOf="parent"
android:visibility="gone"
android:id="@+id/tvContent"
android:layout_width="wrap_content"
android:background="#74c375"
android:layout_height="200dp"
android:text="下面的數據"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
之後設置View的顯示或隱藏都會觸發展開或收縮的動畫效果
val tvOpen = findViewById<TextView>(R.id.tvOpen)
val tvContent = findViewById<TextView>(R.id.tvContent)
var isShow = false
tvOpen.setOnClickListener {
if (isShow.not()) {
tvContent.visibility = View.VISIBLE
} else {
tvContent.visibility = View.GONE
}
isShow = isShow.not()
}