【问题标题】:how to set up an animated toggle button in android如何在android中设置动画切换按钮
【发布时间】:2015-12-23 15:36:02
【问题描述】:

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

编辑: 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。

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

【问题讨论】:

    标签: android togglebutton animationdrawable


    【解决方案1】:

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

    这就是诀窍:

    我的 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);
    

    现在它可以正常加载和运行了。

    【讨论】:

    • 它似乎只适用于具有两种状态的 AnimationDrawable。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2015-07-02
      相关资源
      最近更新 更多