在 Android 中,要實現多選項視圖的動畫效果,可以使用 RecyclerView
和 ItemAnimator
dependencies {
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
data class Option(val text: String, var isSelected: Boolean)
class OptionsAdapter(private val options: List<Option>) : RecyclerView.Adapter<OptionsAdapter.ViewHolder>() {
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.option_text)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.option_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val option = options[position]
holder.textView.text = option.text
holder.textView.setOnClickListener {
option.isSelected = !option.isSelected
notifyItemChanged(position)
}
}
override fun getItemCount(): Int = options.size
}
val recyclerView: RecyclerView = findViewById(R.id.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = OptionsAdapter(listOf(
Option("Option 1", false),
Option("Option 2", false),
Option("Option 3", false)
))
class CustomItemAnimator : DefaultItemAnimator() {
override fun animateChange(
oldHolder: RecyclerView.ViewHolder,
newHolder: RecyclerView.ViewHolder,
fromX: Int,
fromY: Int,
toX: Int,
toY: Int
): Boolean {
if (oldHolder == newHolder) {
val view = oldHolder.itemView
val animator = ValueAnimator.ofFloat(0f, 1f).apply {
addUpdateListener { animation ->
val value = animation.animatedValue as Float
view.scaleX = 1 - value * 0.1f
view.scaleY = 1 - value * 0.1f
if (value >= 0.5f) {
view.alpha = (1 - value) * 2
}
}
duration = changeDuration
interpolator = interpolator
}
animator.start()
return true
}
return super.animateChange(oldHolder, newHolder, fromX, fromY, toX, toY)
}
}
recyclerView.itemAnimator = CustomItemAnimator()
現在,當您點擊選項時,它們將以動畫形式更改其大小和透明度。您可以根據需要調整動畫參數。