简体   繁体   English

android:如何禁用开关动画?

[英]android : how to disable the animation of switch?

Recently,I am using the widget named switch.最近,我正在使用名为 switch 的小部件。 The switch is default widget of Android Studio.The problem is that when I add new Item with switch,its animation will run but I don't want to see it.开关是 Android Studio 的默认小部件。问题是当我用开关添加新项目时,它的动画会运行,但我不想看到它。 I used ListView and Cursor Adapter in my project.And the switch is a item as an element of ListView.我在我的项目中使用了 ListView 和 Cursor Adapter。而 switch 是作为 ListView 元素的一个项目。 Do you know how to solve it?你知道如何解决吗?

如果在开关上调用setChecked()后立即调用jumpDrawablesToCurrentState()将禁用动画。

This is a piece of code from Switch widget (you can see it too - just press Ctrl and click Switch in your Android Studio project window):这是来自 Switch 小部件的一段代码(您也可以看到它 - 只需按 Ctrl 并在您的 Android Studio 项目窗口中单击Switch ):

@Override
public void setChecked(boolean checked) {
    super.setChecked(checked);

    // Calling the super method may result in setChecked() getting called
    // recursively with a different value, so load the REAL value...
    checked = isChecked();

    if (getWindowToken() != null && ViewCompat.isLaidOut(this) && isShown()) {
        animateThumbToCheckedState(checked);
    } else {
        // Immediately move the thumb to the new position.
        cancelPositionAnimator();
        setThumbPosition(checked ? 1 : 0);
    }
}

It will always show animation when visible.它在可见时将始终显示动画。 So you can't disable it.所以你不能禁用它。 But you can extend CompoundButton class and make your own switch widget without any animation.但是您可以扩展CompoundButton类并制作您自己的开关小部件而无需任何动画。

Also you can copy code from Switch widget, rename it, remove animation, make some drawables and you'll get a non-animated switch.您也可以从 Switch 小部件复制代码、重命名、删除动画、制作一些可绘制对象,然后您将获得一个非动画开关。

如果您有不需要的动画,当第一次显示Switch时,那么它可能会帮助您改用SwitchCompat

I was able to disable the animation of the switch by removing it from the view hierarchy, calling setChecked(val) while it's removed, and then readding it to the view hierarchy.我能够通过从视图层次结构中删除它来禁用开关的动画,在它被删除时调用 setChecked(val),然后将它读入视图层次结构。

It's kludgey, but as far as I can tell it's the only way to do it -- you can't subclass Switch to override the setChecked() behavior because you still need to call super.setChecked() which will run Switch#setChecked() and do the animation anyway.它很笨拙,但据我所知,这是唯一的方法——你不能子类化 Switch 来覆盖 setChecked() 行为,因为你仍然需要调用 super.setChecked() 它将运行 Switch#setChecked( ) 并做动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM