更改没有动画的切换状态

时间:2014-11-26 00:20:56

标签: android android-listview android-switch

在我的Android项目中,我有一个ListView,其行包含SwitchCompat项(AppCompat for Switch小部件)。

当我滚动到列表并且使用getView(...)视图调用MyAdapter recycled方法时,会出现问题。我重新定义了正确的Switch状态,但动画是可见的。

在这种情况下有一种防止动画的解决方案吗?

enter image description here

8 个答案:

答案 0 :(得分:45)

调用jumpDrawablesToCurrentState()跳过动画

switchCompat.setChecked(true);
switchCompat.jumpDrawablesToCurrentState();

答案 1 :(得分:12)

我终于找到了一个解决方案,但似乎并不是很干净:

ViewGroup viewGroup = (ViewGroup) view; // the recycled view
viewGroup.removeView(switch);
switch.setChecked(states[index]);
viewGroup.addView(switch);

如果存在更好的解决方案,请分享。

答案 2 :(得分:5)

我遇到了同样的问题,我设法用一些极少的反思来解决它。

<强>用法:

要在没有动画的情况下更改开关状态,请为animate参数调用setChecked(boolean checked, boolean animate)方法,并为false。如果此方法在调用此方法时动画已经动画,则动画将停止并且开关跳转到所需位置。

<强> SwitchCompatFix.java

import android.content.Context;
import android.support.v7.widget.SwitchCompat;
import android.util.AttributeSet;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Work around for: http://stackoverflow.com/questions/27139262/change-switch-state-without-animation
 * Possible fix for bug 101107: https://code.google.com/p/android/issues/detail?id=101107
 *
 * Version 0.2
 * @author Rolf Smit
 */
public class SwitchCompatFix extends SwitchCompat {

    public SwitchCompatFix(Context context) {
        super(context);
        initHack();
    }

    public SwitchCompatFix(Context context, AttributeSet attrs) {
        super(context, attrs);
        initHack();
    }

    public SwitchCompatFix(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initHack();
    }

    private Method methodCancelPositionAnimator = null;
    private Method methodSetThumbPosition = null;

    private void initHack(){
        try {
            methodCancelPositionAnimator = SwitchCompat.class.getDeclaredMethod("cancelPositionAnimator");
            methodSetThumbPosition = SwitchCompat.class.getDeclaredMethod("setThumbPosition", float.class);
            methodCancelPositionAnimator.setAccessible(true);
            methodSetThumbPosition.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public void setChecked(boolean checked, boolean animate){
        // Java does not support super.super.xxx calls, a call to the SwitchCompat default setChecked method is needed.
        super.setChecked(checked);
        if(!animate) {

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

            // Cancel any running animations (started by super.setChecked()) and immediately move the thumb to the new position
            try {
                if(methodCancelPositionAnimator != null && methodSetThumbPosition != null) {
                    methodCancelPositionAnimator.invoke(this);
                    methodSetThumbPosition.invoke(this, checked ? 1 : 0);
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
}

对于proguard用户的注意事项:

由于此方法使用反射,因此可能需要额外的proguard规则(如果尚未存在)。

-keep class android.support.v7.widget.SwitchCompat {
    private void cancelPositionAnimator();
    private void setThumbPosition(float);
}

当您使用以下某个规则(或类似规则)时,不需要此附加规则:

-keep class android.support.v7.widget.** { *; }
-keep class android.support.v7.** { *; }

答案 3 :(得分:3)

使用SwitchCompat和DataBinding

@BindingAdapter({"bind:checkedState"})
public static void setCheckedState(SwitchCompat switchView, boolean checked) {
    int visibility = switchView.getVisibility();
    switchView.setVisibility(View.INVISIBLE);
    switchView.setChecked(checked);
    switchView.setVisibility(visibility);
}

然后在xml:

<android.support.v7.widget.SwitchCompat
    android:id="@+id/my_switch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:checkedState="@{my_data.checked}"/>

不要忘记致电executePendingBindings()(感谢AAverin

答案 4 :(得分:2)

如果您使用Android数据绑定,则可能会出现列表中播放动画的问题。

要解决此问题,请在设置数据后运行binding.executePendingBindings()方法 - 它将刷新当前帧中组件的绑定状态,并且不会等待下一个组件的绑定状态。

正如您可能已经猜到的那样 - 下一帧是动画

答案 5 :(得分:1)

对于Kotlin开发者:

fun SwitchCompat.setCheckedWithoutAnimation(checked: Boolean) {
    val beforeVisibility = visibility
    visibility = View.INVISIBLE
    isChecked = checked
    visibility = beforeVisibility
}

用法:

mySwitch.setCheckedWithoutAnimation(true)

答案 6 :(得分:0)

就我而言,我正在使用新的材料库:

implementation 'com.google.android.material:material:1.1.0-alpha07'

,并且在此类的setChecked方法中,存在以下条件:

if (getWindowToken() != null && ViewCompat.isLaidOut(this))

所以我要做的是创建一个从此SwitchMaterial扩展的类,并处理“ isLaidOut”。该代码是下一个代码(省略构造函数):

class SwitchCustomView : SwitchMaterial {

  private var laidOutForAnimation: Boolean

  init {
    laidOutForAnimation = false
  }

  fun setChecked(checked: Boolean, animate: Boolean) {
    if (!animate) {
      laidOutForAnimation = true
    }
    super.setChecked(checked)
    laidOutForAnimation = false
  }

  override fun isLaidOut(): Boolean {
    return if (laidOutForAnimation) {
      return false
    } else {
      super.isLaidOut()
    }
  }
}

然后只需在xml中使用此类并以编程方式调用

setChecked(checked: Boolean, animate: Boolean)

答案 7 :(得分:0)

Rolf ツ 答案的 Kotlin 示例。

class SwitchImproved(context: Context, attributeSet: AttributeSet) : SwitchCompat(context, attributeSet) {

    private lateinit var methodCancelPositionAnimator: Method
    private lateinit var methodSetThumbPosition: Method

    init {
        initHack()
    }

    fun setChecked(checked: Boolean, animate: Boolean = true) {
        super.setChecked(checked)

        if (!animate) {
            methodCancelPositionAnimator.invoke(this)
            methodSetThumbPosition.invoke(this, if (isChecked) 1 else 0)
        }
    }

    private fun initHack() {
        methodCancelPositionAnimator = SwitchCompat::class.java.getDeclaredMethod("cancelPositionAnimator")
        methodSetThumbPosition = SwitchCompat::class.java.getDeclaredMethod("setThumbPosition", Float::class.javaPrimitiveType)
        methodCancelPositionAnimator.isAccessible = true
        methodSetThumbPosition.isAccessible = true
    }
}