2

I have spent more than 10 hours trying to get the animation of the switch to work.

I have tried so many things that I don't remember several of the attempts, but I'll explain those that I remember.

Code that should work (I think):

I use the widgetLayout parameter:

<CheckBoxPreference
    android:defaultValue="false"
    android:key="asd"
    android:title="@string/asd"
    android:widgetLayout="@layout/switchcompat_for_settings">

switchcompat_for_settings:

<android.support.v7.widget.SwitchCompat
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@null"
    android:clickable="false"
    android:focusable="false"
    android:gravity="center"
    />

No animation.

Extending SwitchCompat with this code (best attempt??): https://gist.github.com/antifriz/ad4412b72d50f63ec977

Going from false to true there is an animation, going from true to false there is no animation.

Non ideal behaviour (but acceptable, if it can't be prevented): if the value is true it plays animation when the activity is loaded.

Extending with following code:

Extending Preference classes in Android Lollipop = losing animation

No animation at all.

@Override
public boolean isShown() {
    return getVisibility() == VISIBLE;
}

Using SwitchPreference:

Before Lollipop it has the old view, so not ideal because I would need different xml for before Lollipop and after. If I have only one SwitchPreference I still have no animation. With several consecutive SwitchPreferences I get an animation in all but one (I've also checked with a new project with the Settings template and same problem).

Also, I prefer no animation in any Preference than animation in all but one.

Adding a second Switch:

In switchcompat_for_settings I add a second SwitchCompat and set the one with id=@android:id/checkbox to invisible. I extend the CheckboxPreference to override onBindView, and after calling super.onBindView I find the extra SwitchCompat and call setChecked to the appropriate value.

In the onPreferenceClick I call the setChecked of my extra switch.

It toggles without animation. My understanding is that the problem is that as onBindView is called A LOT of times (when creating the preference, and also each time I toggle it), it cancels the animation.

I tried to add a boolean to call setChecked in onBindView only after being called from onClick but did not succeed. Maybe it is the way to go and I did something wrong.

Only remaining idea (not willing to do this): Add the switch manually to the activity root view, place in the correct position and handle from each activity that has this preference (several).

lotdrops
  • 300
  • 5
  • 16

0 Answers0