Android 快速实现View的展开和收缩效果

发布时间 2023-12-25 13:38:55作者: Stars-one

原文: Android 快速实现View的展开和收缩效果 - Stars-One的杂货小窝

看到一篇文章用到了一个布局的属性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()
}