在 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()
现在,当您点击选项时,它们将以动画形式更改其大小和透明度。您可以根据需要调整动画参数。