Jojo Ilkischmilki Jojo Ilkischmilki - 1 year ago 182
Android Question

Android SwitchCompat play animation on toggle() or setChecked()

I added a SwitchCompat to my Drawernavigation in Android.

First I set the item's actionlayout to my switchlayout.xml:

< xmlns:android=""
app:switchPadding="16dp" />

Now I'm trying to change the Buttons checkedstate in my Code, I'm trying
and also tried

But it only changes the Color of the Switch, but doesn't play the animation where the Switch moves from one side to the other. How do I play this animation from my code?

Answer Source

I faced the same issue. It seems that SwitchCompat is broken on this point. setChecked() calls the animator that should update the thumb drawable but the onAnimationEnd is never called.

Meanwhile after many tries faking the touch events send to the SwitchCompat, I found an ugly workaround : instead of calling setChecked(), I remove the item from the menu and add it again :

// Update toggle state
final SwitchCompat toggle = (SwitchCompat) LayoutInflater.from(this).inflate(R.layout.drawer_menu_item_availability, null);
toggle.setOnCheckedChangeListener((buttonView, isChecked) -> toggleAvailability());
final MenuItem added = mDrawerView.getMenu().add(,, Menu.FIRST, text);

This however forces you to :

  • have an id for the menu group where your menu item is located
  • use android:orderInCategory to order your menu items so that your item goes back to the same place when adding it back.

Hope this helps.

EDIT : This does not play the animation but at least the thumb is in the right place.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download