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?
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 :
Hope this helps.
EDIT : This does not play the animation but at least the thumb is in the right place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With