Custom Button Animation in Android

拈花ヽ惹草 提交于 2019-12-08 03:04:27
Vitaly Zinchenko

You can do something like this:

  1. Create a file button_state_list_anim.xml and put it into anim folder (if you haven't got it, create it in your res folder)
  2. Add these lines to the file:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="true"
        android:state_pressed="true">
        <set>
            <objectAnimator
                android:duration="100"
                android:propertyName="scaleX"
                android:valueTo="1.3"
                android:valueType="floatType" />
            <objectAnimator
                android:duration="100"
                android:propertyName="scaleY"
                android:valueTo="1.3"
                android:valueType="floatType" />
        </set>
    </item>
    <!-- base state -->
    <item android:state_enabled="true">
        <set>
            <objectAnimator
                android:duration="100"
                android:propertyName="scaleX"
                android:startDelay="100"
                android:valueTo="1"
                android:valueType="floatType" />
            <objectAnimator
                android:duration="100"
                android:propertyName="scaleY"
                android:startDelay="100"
                android:valueTo="1"
                android:valueType="floatType" />
        </set>
    </item>
    <item>
        <set>
            <objectAnimator
                android:duration="0"
                android:propertyName="scaleX"
                android:valueTo="1"
                android:valueType="floatType" />
            <objectAnimator
                android:duration="0"
                android:propertyName="scaleY"
                android:valueTo="1"
                android:valueType="floatType" />
        </set>
    </item>
    

  3. In layout files where you use the button, add android:stateListAnimator= "@anim/custom_button_state_list_anim_material", for example

    <Button android:id="@+id/animated_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:stateListAnimator="@anim/custom_button_state_list_anim_material" android:text="Animated button" />

add onTouchListener:

 button.setOnTouchListener(new View.OnTouchListener()
 {
                @Override
                public boolean onTouch(View v, MotionEvent event) 
                {

                  if (event.getAction() == MotionEvent.ACTION_DOWN)
                   {
                      here the button is pressed down
                   }



                    return false;
                }
            });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!