Jojo Ilkischmilki Jojo Ilkischmilki - 4 months ago 54
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:

<android.support.v7.widget.SwitchCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="right|center_vertical"
app:buttonTint="@color/colorPrimary"
app:switchPadding="16dp" />


Now I'm trying to change the Buttons checkedstate in my Code, I'm trying
switchCopmatObj.toggle()
and also tried
switchCompatObj.setChecked(!switchCompatObj.isChecked())


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

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
mDrawerView.getMenu().removeItem(R.id.drawer_menu_availability);
final SwitchCompat toggle = (SwitchCompat) LayoutInflater.from(this).inflate(R.layout.drawer_menu_item_availability, null);
toggle.setChecked(mAvailable);
toggle.setOnCheckedChangeListener((buttonView, isChecked) -> toggleAvailability());
final MenuItem added = mDrawerView.getMenu().add(R.id.drawer_menu_group_actions, R.id.drawer_menu_availability, Menu.FIRST, text);
added.setActionView(toggle);

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.