Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 492
Jonathan Avatar asked Feb 15 '26 11:02

Jonathan


1 Answers

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.

like image 110
Jules Tréhorel Avatar answered Feb 19 '26 04:02

Jules Tréhorel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!