2

我创建了一个动画切换按钮,就像有人在这个SO question 中所做的那样。它工作正常但有一个小问题,当第一次创建布局时,我的切换按钮背景是动画绘制的第一帧(它应该是它的最后一帧)。一旦我第一次点击它,它就可以正常工作。

编辑:toggle_pause_anim.xml:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true" >

<item
    android:drawable="@drawable/pause1"
    android:duration="50"/>
...
<item
    android:drawable="@drawable/pause20"
    android:duration="50"/>

</animation-list>

toggle_pause_anim.xml:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true" >

<item
    android:drawable="@drawable/play1"
    android:duration="50"/>
...
<item
    android:drawable="@drawable/pause20"
    android:duration="50"/>

</animation-list>

toggle_play_pause_anim.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/toggle_play_anim" android:state_checked="false"/>
<item android:drawable="@drawable/toggle_pause_anim" android:state_checked="true"/>

</selector>

toggle_play_pause_bg:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@+android:id/background"
    android:drawable="@android:color/transparent"/>
<item
    android:id="@+android:id/toggle"
    android:drawable="@drawable/toggle_play_pause_anim"/>

</layer-list>

ToggleButton在我的 layout.xml 中:

<ToggleButton
    android:id="@+id/play_pause"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toggle_play_pause_bg"
    android:textOff=""
    android:textOn="" />

不,我确实在创建时将检查设置为 false。

是我得到的视频。问题是第一次加载布局时(图标应该是播放,而不是暂停)。如您所见,在第一次更改之后,它可以正常工作。

4

2 回答 2

3

好吧,由于没有人回答,我搜索了又搜索,终于找到了解决方案。

所以这里的诀窍是:

我的 layout.xml 中的切换按钮:

<ToggleButton
    android:id="@+id/play_pause"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toggle_play_pause_anim"
    android:textOff=""
    android:textOn="" />

事实证明,layer drawable 是不必要的,在 java 代码中,我在onCreate方法中添加了这些行:

toggleBtn = (ToggleButton) findViewById(R.id.play_pause);
StateListDrawable stateListDrawable = (StateListDrawable) toggleBtn.getBackground();
AnimationDrawable animationDrawable = (AnimationDrawable) stateListDrawable.getCurrent();
animationDrawable.selectDrawable(animationDrawable.getNumberOfFrames() - 1);

现在它加载并运行得很好。

于 2015-12-24T20:34:30.680 回答
0

请添加您的代码,但您似乎应该在 Activity 的 onCreate 方法中使用 setChecked(true) 或 setChecked(false)。

于 2015-12-23T16:23:35.093 回答