はじめに
ValueAnimator
を使用してビューの高さを変更するアニメーションの作成方法について記述。ここでは、折り畳みビューを作成し、高さ変更時にアニメーションを付与する。
レイアウト作成
トグルボタンで折り畳みを行うようにする。高さを変更するビューはConstraintLayout部分。
activity_main.xml
<?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=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/view"
android:layout_width="0dp"
android:layout_height="24dp"
android:layout_margin="24dp"
android:background="@color/gray"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ToggleButton
android:id="@+id/button"
android:layout_width="24dp"
android:layout_height="24dp"
android:background="@drawable/button"
android:checked="false"
android:textOff=""
android:textOn=""
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
処理部分作成
ValueAnimator
を用いてアニメーション処理を実装。
MainActivitiy.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//トグルボタン押下時
binding.button.setOnCheckedChangeListener { _, b ->
//開く場合:高さ1000pixel / 閉じる場合:高さ24dp
val height = if (b) 1000 else (24 * resources.displayMetrics.density).toInt()
val anim = ValueAnimator.ofInt(binding.view.measuredHeight, height)
anim.addUpdateListener { valueAnimator ->
val layoutParams = binding.view.layoutParams
layoutParams.height = valueAnimator.animatedValue as Int
binding.view.layoutParams = layoutParams
}
anim.duration = 300
anim.start()
}
}