问题
I have a ViewAnimator
(ViewSwitcher
to be precise) with fade in/out animations associated to it and two Views
which I transition between using the ViewAnimator.showNext()
and ViewAnimator.showPrevious()
methods.
There is a requirement in my app where sometimes I need to start straight from the second View
, without showing a fade animation in going from the first View
to the second. Anyone know if there is a straightforward way to accomplish this without having to mess around with the in/out animations associated to my ViewAnimator
?
Note: I have tried calling
ViewAnimator.setDisplayedChild(1)
but that also animates the transition.
回答1:
I looked around and waited for a response but I'm guessing it's not possible. So, in the absence of a better solution, set your ViewAnimator
's in/out animations to null when you want to jump straight to a particular child View
of your ViewAnimator
, as follows:
myViewAnimator.setInAnimation(null);
myViewAnimator.setOutAnimation(null);
myViewAnimator.setDisplayedChild(childIndex);
If anyone knows a better way - rather than playing with the ViewAnimator
's in/out animations - please share!
回答2:
Unfortunately, there is no built-in function to do that, but you can add this function, which does the job:
public static void setDisplayedChildNoAnim(ViewAnimator viewAnimator, int whichChild) {
Animation inAnimation = viewAnimator.getInAnimation();
Animation outAnimation = viewAnimator.getOutAnimation();
viewAnimator.setInAnimation(null);
viewAnimator.setOutAnimation(null);
viewAnimator.setDisplayedChild(whichChild);
viewAnimator.setInAnimation(inAnimation);
viewAnimator.setOutAnimation(outAnimation);
}
回答3:
Here's a more comprehensive way, which let you choose either an id or a view, and with/without animation:
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
}
Example of usage:
viewSwitcher.setViewToSwitchTo(someView,false)
来源:https://stackoverflow.com/questions/11231933/possible-to-jump-straight-to-second-view-in-viewanimator