这是一种更全面的方法,它让您可以选择一个 id 或一个视图,以及有/没有动画:
fun ViewAnimator.setViewToSwitchTo(viewToSwitchTo: View, animate: Boolean = true): Boolean {
if (currentView === viewToSwitchTo)
return false
for (i in 0 until childCount) {
if (getChildAt(i) !== viewToSwitchTo)
continue
if (animate)
displayedChild = i
else {
val outAnimation = this.outAnimation
val inAnimation = this.inAnimation
this.inAnimation = null
this.outAnimation = null
displayedChild = i
this.inAnimation = inAnimation
this.outAnimation = outAnimation
}
return true
}
return false
}
fun ViewAnimator.setViewToSwitchTo(@IdRes viewIdToSwitchTo: Int, animate: Boolean = true): Boolean {
if (currentView.id == viewIdToSwitchTo)
return false
for (i in 0 until childCount) {
if (getChildAt(i).id != viewIdToSwitchTo)
continue
if (animate)
displayedChild = i
else {
val outAnimation = this.outAnimation
val inAnimation = this.inAnimation
this.inAnimation = null
this.outAnimation = null
displayedChild = i
this.inAnimation = inAnimation
this.outAnimation = outAnimation
}
return true
}
return false
}
使用示例:
viewSwitcher.setViewToSwitchTo(someView,false)