Android SwitchCompat 在 toggle() 或 setChecked() 上播放动画
Android SwitchCompat play animation on toggle() or setChecked()
我在 Android 的 Drawernavigation 中添加了 SwitchCompat。
首先我将项目的操作布局设置为我的 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" />
现在我正在尝试更改代码中的按钮检查状态,我正在尝试 switchCopmatObj.toggle()
并且还尝试了 switchCompatObj.setChecked(!switchCompatObj.isChecked())
但它只是改变了Switch的颜色,并没有播放Switch从一侧移动到另一侧的动画。如何从我的代码中播放此动画?
我遇到了同样的问题。 SwitchCompat 似乎在这一点上被打破了。 setChecked() 调用应更新拇指可绘制对象的动画师,但从未调用 onAnimationEnd。
同时,在多次尝试伪造发送到 SwitchCompat 的触摸事件后,我发现了一个丑陋的解决方法:而不是调用 setChecked() ,我从菜单中删除该项目并再次添加它:
// 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);
然而,这迫使您:
- 为您的菜单项所在的菜单组设置一个 ID
- 使用 android:orderInCategory 来订购您的菜单项,以便您的菜单项在添加回来时返回到相同的位置。
希望对您有所帮助。
编辑:这不会播放动画,但至少拇指在正确的位置。
我在 Android 的 Drawernavigation 中添加了 SwitchCompat。
首先我将项目的操作布局设置为我的 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" />
现在我正在尝试更改代码中的按钮检查状态,我正在尝试 switchCopmatObj.toggle()
并且还尝试了 switchCompatObj.setChecked(!switchCompatObj.isChecked())
但它只是改变了Switch的颜色,并没有播放Switch从一侧移动到另一侧的动画。如何从我的代码中播放此动画?
我遇到了同样的问题。 SwitchCompat 似乎在这一点上被打破了。 setChecked() 调用应更新拇指可绘制对象的动画师,但从未调用 onAnimationEnd。
同时,在多次尝试伪造发送到 SwitchCompat 的触摸事件后,我发现了一个丑陋的解决方法:而不是调用 setChecked() ,我从菜单中删除该项目并再次添加它:
// 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);
然而,这迫使您:
- 为您的菜单项所在的菜单组设置一个 ID
- 使用 android:orderInCategory 来订购您的菜单项,以便您的菜单项在添加回来时返回到相同的位置。
希望对您有所帮助。
编辑:这不会播放动画,但至少拇指在正确的位置。