【问题标题】:Android: Background drawable not rotating when rotating ToggleButtonAndroid:旋转ToggleButton时背景drawable不旋转
【发布时间】:2023-05-08 07:33:01
【问题描述】:

我目前正在使用一组具有多个状态背景资源和旋转动画的 ToggleButtons。一切正常,直到按下切换按钮,发生这种情况:

  1. 当按钮获得焦点时,它会重新绘制,但会处于原始状态,就像它在旋转 0 时一样。
  2. 释放按钮时,它会尝试使用真实值背景重新绘制新背景,但由于使用原始切换按钮高度作为宽度,因此图像宽度被裁剪。
  3. 当按钮再次获得焦点时,会发生与 1) 相同的问题。
  4. 释放按钮后,它会正确重绘。

到目前为止,我现在的问题是原始可绘制对象没有旋转,因此出现了这种行为。我目前的解决方案是为每个旋转使用三个不同的切换按钮(90°、0°、-90°),动画并隐藏当前按钮,然后显示新按钮(使用相同的可绘制对象并使用 XML 旋转它们标签),但我觉得有点麻烦......

这是用于 90° 动画的 XML:

<rotate
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:interpolator="@android:anim/linear_interpolator"
  android:fromDegrees="0"
  android:toDegrees="90"
  android:pivotX="50%"
  android:pivotY="50%"
  android:duration="250"
  android:fillAfter="true"
  android:fillEnabled="true" >
</rotate>

ToggleButton 背景的 XML:

<?xml version="1.0" encoding="utf-8"?>  
<selector xmlns:android="http://schemas.android.com/apk/res/android">  
 <item android:drawable="@drawable/record_button_on_pressed" 
    android:state_checked="true" android:state_pressed="true"/> 
 <item android:drawable="@drawable/record_button_pressed" android:state_checked="true" 
    android:state_focused="false"/> 
 <item android:drawable="@drawable/record_button_on_press" 
    android:state_checked="false" android:state_pressed="true"/> 
 <item android:drawable="@drawable/record_button" android:state_checked="false"
    android:state_focused="false"/>
</selector>  

以及用于旋转视图的代码:

RotateAnimation rotate = (AnimationUtils.loadAnimation(this, 
    R.anim.rotation90deg);
startStopRecording.startAnimation(rotate);

希望你们能帮助我。

【问题讨论】:

  • 一些代码会有所帮助。
  • 您能展示一下您是如何进行轮换的吗?如果你旋转按钮,那么drawable也应该被旋转。
  • drawable 已正确旋转,但是当执行焦点或状态更改时,视图显示错误。还在原题上添加了相应的代码。

标签: android rotation android-animation togglebutton


【解决方案1】:

看来我使用了错误的方法。 Pre 3.0 动画不会为当前视图设置动画,但会创建此类视图的 Bitmap 并对其进行动画处理;所以最后,转换后的视图只是一个图像,所以我得到的行为是。

无论如何,通过使用 android animator,我能够旋转并保持按钮旋转(实际视图),以便正确绘制按钮(按下时)。一个小缺点是您必须放弃所有 3.0 之前的 android 设备。但是,如果你真的需要支持这样的版本,你可以使用NineOldAndroid 项目。

【讨论】: