安卓如何实现button原生的漂浮动画效果?

安卓原生的Button在点击时会有一个如同纸片漂浮与阴影的动画效果,我该如何实现呢?
我还想在获取焦点时实现这个动画效果,我该如果去做?
如果我在TextView上也想实现这个效果呢?

img

小魔女参考了bing和GPT部分内容调写:
要实现Button的原生漂浮动画效果,需要使用Android的StateListAnimator类。StateListAnimator类允许我们定义一系列的动画,当控件的状态发生变化时,可以播放不同的动画。

首先,我们需要在res/animator/目录下创建一个xml文件,用来定义漂浮动画的动画属性,例如:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <objectAnimator
            android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ"
            android:valueTo="4dp"
            android:valueType="floatType" />
    </item>
    <item>
        <objectAnimator
            android:duration="@android:integer/config_shortAnimTime"
            android:propertyName="translationZ"
            android:valueTo="0dp"
            android:valueType="floatType" />
    </item>
</selector>

然后,我们可以在Button的XML布局文件中,设置StateListAnimator属性,指定我们刚刚定义的动画:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:stateListAnimator="@animator/button_elevation_animator" />

最后,当Button获取焦点时,我们可以使用Button的setOnFocusChangeListener方法,来播放动画:

button.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus) {
            view.animate().scaleX(1.1f).scaleY(1.1f).setDuration(200).start();
        } else {
            view.animate().scaleX(1.0f).scaleY(1.0f).setDuration(200).start();
        }
    }
});

以上就是实现Button原生漂浮动画效果的方法,通过使用StateListAnimator类和setOnFocusChangeListener方法,可以轻松实现Button的动画效果。
回答不易,记得采纳呀。

你可以用button代替TextView

https://blog.csdn.net/dong19900415/article/details/78690085自定义selector